What is a constant variable 4

C tutorial (C or C ++, preface, installation, chapters 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)

Variables and constants, assignment

Last update: October 10, 2009

2.1. Declare variables and constants

Data must be saved continuously while the program is running or data must be read in. When the user makes an entry, this entry must be saved somewhere in order to be able to evaluate it later. There are basically two options for storing data: storage in the main memory or in a file. A Database is ultimately just a file.

The random access memory has two main problems: it is volatile, the data will be lost at the latest when you switch off the PC. And its capacity is usually too limited to accommodate large amounts of data in it. The latter is increasingly put into perspective by falling prices for memory modules, but compared to hard drive sizes it is still "small". In addition, the demands on the computing power always increase. :-)

But the main memory has one advantage: It is fast! Much faster than any hard drive. How fast depends on the type of memory and its construction. In principle: ever closer the processor, the faster the memory module should be. So L1 cache before L2 cache before RAM modules. However, we shall not concern ourselves with this topic any further here.

In order to process data, you will always load it into the working memory. At least part of it, depending on the size of the data and the available memory. If data is to be available even after the end of the program, it is stored in a file or transferred to a database management system. I cover file access in Chapter 13 of this tutorial.

Now to the actual topic: In order to store data in the working memory, one needs in the programming variables. You are probably familiar with variables from mathematics. Here they stand for placeholders. It's similar in programming. One variable reserved a certain amount of space in memory. A variable can thus reserve around two bytes in which data can then be stored.

Variables can be of different types (Data types) be. Depending on the type, the reserved storage space is different in size and different data can be saved. So have variables of type int a size of 2 or 4 bytes. How much exactly depends on the Word length the processor register and the compiler used. A register is an internal memory location of a processor. This is the fastest available memory for the CPU. For this, the number of registers and thus the memory size is severely limited. In other words: there are only a few.

You can use to determine how much memory a variable actually requires on your system sizeof- Determine operator (more on this later). Depending on the type, not only a different size storage space is reserved, but different values ​​can also be saved. So can int about only Integers (about -10, 12 or 20007; You will see later that characters like "a" can also be stored as a number) while variables of type floatFloating point numbers (Floating point numbers; about 1.3, 40.345313) be able to record.

Of variables are Constants to distinguish. A constant corresponds to a variable, but with a fixed, non-changeable value. This means that a constant must be initialized (defined) when it is declared. So if you want a constant, you have to assign a value to it right away. And it keeps this as long as it exists (which does not necessarily have to be until the end of the program).

C compilers will not complain (no error, no warning) if you omit the initialization, but you will not be able to do anything with the constant later. Try about the constant a assign a value, you will get the error message from GCC, for example: Error: Assignment of the read-only variable "a". You only have the "chance" with the declaration.

Under one declaration one understands the Announcement to the compiler that something (here: the variable) exists. Becomes a of type int declared, the compiler knows: The variable a exists and has the type int. Becomes a variable in front their use, especially when a value is assigned when the declaration is made (i.e. an initial value), is called a initialization.

If a value is assigned, one speaks of a definition. An initialization is a special form of definition. So much for the linguistic subtleties that had to be mentioned. :-)

declarationAnnouncement, e.g. inform the compiler that a variable exists, what identifier (name) it has and what type it is.
definitionValue assignment, e.g. a previously declared variable is now assigned a value.

In order to declare a variable, you need to know two things:

  1. What do I want to call my variable? Each variable needs a name (identifier) ​​with which it can be addressed.
  2. What type should my variable be? Depending on which values ​​are to be saved, a different type must be selected. Sometimes it is also necessary to consider the storage space consumption.

When choosing the name (identifier) ​​you are bound by a few rules. The name may only be from alphanumeric characters (such as "a", "X" or "3"; BUT NOT "§" or "$") as well as the Underscore"_" consist. The name must begin with a letter or an underscore. So there can be no number at the beginning of the name.

According to the standard, the identifier should not contain more than 32 characters. In addition, there are a few other things to consider that make sense, but are not mandatory. The identifier should be as meaningful as possible so that you can also later know what the variable is for. With variables like a, k1, j and y3 is it difficult.

The identifier should therefore show what purpose the variable serves. The purpose of data storage is of course clear, but the question arises, Which Data should be saved and when and for what purpose the variable is used. However, try to keep the length of the identifier as short as possible. So as short as possible, as long as necessary.

So better counter as This is my count variable as an identifier. Counting variables are often also referred to by letters i, j, k, etc. So here it would only do i (how index).

Let's look at a variable declaration:

The type of integer int you already know. The variable of this exists after this line i. The declaration is followed by a semicolon ; completed. In general it can be said:

In one line you can easily several Declare variables. Example:

As you can see, the individual identifiers only have to be separated by commas. In the example above, the variables a, b and c of type int declared (each has the type int). However, if you also need one or more variables from one other Type, this declaration must be on a separate line. Such as:

The variable z of type char declared. There char another type than int the declaration must be on a line of its own. In principle, you could also write the second declaration on the same line as long as it comes after the semicolon. There is also the semicolon.

IMPORTANT: In ANSI-C (C89 / C90) it is not allowed to simply declare variables somewhere to be accommodated in the statement block. Declarations must ALWAYS be at the beginning of an instruction block. Example:

int main () {int a, b, c; char z; / * Only now do more instructions follow ... * / return0;}

Attention: The next two programs each contain an error!
These examples will not work with real (older) C compilers.

Example 1:

#include int main () {/ * ERROR: Program code BEFORE the variable declaration! * / printf ("The program has started ..."); int a, b, c; / * The declaration is only made here ... * / char z; / * Only now do more instructions follow ... * / return0;}

Example 2:

int main () {; int a, b, c; / * pay attention to the semicolon at the beginning! * / char z; / * Only now do more instructions follow ... * / return0;}

You will probably find the error more easily in example 1 than in example 2. In the first example, an entire "meaningful" statement precedes the variable declaration. In the second example, the debugging programmer has a much harder time. The only thing out of place here is a "lost" semicolon. It stands in front the variable declaration and is therefore considered by the compiler as a complete statement. Hence a mistake.

By the way: The line / * Only now do more instructions follow * / is with /* and */ as comment marked. Comments are made by the compiler ignored. I'll go into that in more detail in Chapter 4.

Now to the practice: All of the "wrong" examples above work with GCC - without error messages, without warnings. This is because GCC is also a C ++ compiler and also supports the newer C standards. As of C99, it is no longer necessary for variable declarations to be at the beginning of the statement block. Not in C ++ anyway. Even with the command line parameter -std = c89 the source code can be translated easily. GCC should still allow newer extensions as long as they do not conflict with the old C standard. The "error simulation" is only perfect if you also add the parameters -pedantic complete.

If you want to test an old, antique C compiler, you can Borland Turbo C try out. But please do not direct any complaints to me if something does not work as expected (or Turbo C does not work at all). ;-) Version 2 of Turbo C dates back to 1989. Turbo C is also guaranteed not to know any new standards.

Although it does not matter in practice, variable declarations are always placed at the beginning of an instruction block in this tutorial. If you pure If you want to write C code, you should too.

A constant is declared by placing the keyword in front of the type const put. keywords are reserved identifiers. These are names you Not may use as an identifier. For example, you are not allowed to declare a variable with the name "const". An example of a constant:

Here became the constant PI declared and initialized (defined). Otherwise, the same applies here as for the declaration of variables.

2.2. Data types

Now let's look at the individual data types. In C, a distinction is made between integer and floating point types. The types of integers include char, short int, int and long int. The floating point types include float, double and long double.

One of the 4 types of integers can be signed (signed) and a unsigned (unsigned) Variable or constant can be declared. By default, all integer types are signed (signed). This means that you can save negative as well as positive numbers. With the keyword signed you can mark this separately in front of the type. Whether you are now

or

write is indifferent.

But you just want to positive You can store integers using an unsigned type unsigned declare:

The advantage is that unsigned-Types bigger Can represent numbers. The reason for this is that with signed-Types the most significant bit as Sign bit is used. At unsigned however, it can be used to represent the number.

By the way, it doesn't matter if you are long int or long write. Likewise can take place short int only short be used.

The following table lists all data types that you can specify when declaring a variable or constant as a type. The range indicates the smallest and largest possible number that can be stored. The size describes the storage space consumption in the main memory.

Integer types:

TypeAreaUsual size
signed char-128 to 1271 byte
unsigned char0 to 2551 byte
short int-32768 to 32767 (if 2 bytes)2 or 4 bytes
unsigned short int0 to 65535 (if 2 bytes)2 or 4 bytes
int-2147483648 to 2147483647 (if 4 bytes)2 or 4 bytes
unsigned int0 to 4294967295 (if 4 bytes)2 or 4 bytes
long int-2147483648 to 2147483647 (if 4 bytes)4 or 8 bytes
unsigned long int0 to 4294967296 (if 4 bytes)4 or 8 bytes

The data type long often has 8 bytes (= 64 bit) on 64-bit systems. The size of the integer types is not specified in ANSI-C. However, the following order applies:

char <= short <= int <= long

The guy short must be there at least 2 bytes and longat least 4 bytes. If you are interested in the exact size on your system, you can look at the header file limits.h take a closer look. But, as mentioned, it's easier with the sizeof-Operator. More on this in Chapter 4.

Floating point types:

TypeAreaaccuracysize
float1.2 * 10-38 up to 3.4 * 10386 digits4 bytes
double2.3 * 10-308 up to 1.7 * 1030815 digits8 bytes
long double3.4 * 10-4932 until 1.1 * 10493219 positions10 bytes

Since you will come across the data types again and again in the course of this tutorial, I will spare myself more detailed examples at this point.

2.3. allocation

After a variable has been declared, you can determine which value it should store. This process of telling the variable what value to store is known as allocation. Example:

Let's assume the variable i be of the type intthen this becomes the value 10 (an integer) assigned. Afterwards save the variable i this value. In general it can be said:

Instead of variable insert the identifier of the variable to which you want to assign a value. To the right of the identifier follows the Assignment operator=. The assignment operator ensures that data is "transported" to the variable and signals that it is an assignment. To the right of the assignment operator is the value that the variable is to store. Another variable can be located here, then the value of the right variable is assigned to the left variable, i.e. into the left variable copied.

So it always will transferred from right to left. IMPORTANT: The assignment operator = is not a comparison for equality! Though owns to of the assignment, the variable on the left is the value on the right, but of these is the Equality operator (==), which you will get to know later, must be strictly differentiated!

The importance of the = in C is therefore different from what you are probably familiar with from mathematics.

You have already learned about the initialization of variables when they are declared. Here again to repeat:

For example:

If several variables of the same type are agreed, it is also possible to initialize only some of them. An example:

Here we declare the variables i, j, k and l. The variables j and k we assign values ​​immediately, not to the others.

The assignment is very important when declaring constants. Without assignment, constants would be useless.

After that the constant exists repetitions with the fixed value 10 and the constant mode with the value 1.

2.4. Areas of validity

In C it is possible to declare local and global variables. So there are two different ones Areas of validity. The scope indicates Where a variable exists and is "visible".

A local variable (or constant) becomes within of a statement block, such as that of a function. So far we only have local variables in the Main()Function declared. These are only valid in this function. That is, another function (if you had one) cannot access these variables. The same applies to constants. These variables and constants do not exist for another function.

What is important is you local Initialize variables before using them! The value that local variables have is not predictable! In other words: at the beginning any Value in a local variable. This can be 0, but also any other value. And that is seldom desired.

A local variable is only valid (available) when the function in which it was declared is called.If the function is terminated, the variable is no longer available. This is why it is beneficial for local variables if you assign a value to them immediately when they are declared, in order to avoid unpredictable results. The best thing to do is to simply initialize each variable with 0.

With 0 (Zero) will namely global variables initialized by default. Global variables are in the entire program, therefore in all Functions valid. It is best to write the declaration as far as possible at the top of the source code to keep things clear.

#include int global_variable; / * is initialized with 0 and is valid in the entire program * / int main () {int local_variable; / * is initialized with a non-predictable value and is only valid in main () * / printf ("Local:% d \ n", local_variable); / * output the value of the local variable * / printf ("Global:% d \ n", global_variable); / * output the value of the global variable * / return0;}

The exact explanation too printf () I'll deliver in Chapter 3. Let me just anticipate this: That % d ensures that an integer is output. In this case the first parameter that was specified after the text (string). With \ n becomes a line break (new line) generated.

You can local Declare variables with the same name as already declared global Own variables. In this case you always "see" the local variable, as the following example shows:

#include int i = 10; / * global variable i with the value 10 * / int main () {int i = 50; / * local variable, which is also called i * // * i becomes 50 initialized * / printf ("value of i:% d \ n", i); / * output i * / return0;}

Which value will be shown in the example? Check it out for yourself!