Why should we initialize a variable before using it?

Possible duplicate:
What happens to a declared, uninitialized variable in C? Does it matter?

Now I read Teach Yourself C in 21 Days . Chapter 3 has this note:

DO NOT use a variable that has not been initialized. Results may be unpredictable.

Please explain to me why this is so. The book does not provide any further explanation.

+7
source share
6 answers

When a variable is declared, it points to a piece of memory.

Accessing the value of a variable will give you the contents of this piece of memory.

However, until the variable is initialized, this part of the memory can contain anything. That is why its use is unpredictable.

Other languages ​​can help you in this area by automatically initializing variables when you assign them, but as a C programmer you work in a rather low-level language that makes no assumptions about what you want to do with your program. You, as a programmer, must explicitly tell the program to do everything.

This means initializing the variables, but it also means much more. For example, in C, you need to be very careful that you allocate any resources that you allocate when you are done with them. Other languages ​​will be automatically cleaned upon completion of the program; but in C, if you forget, you just end the memory leak.

C will allow you to do many things that would be difficult or impossible in other languages. But this power also means that you must take responsibility for homework that you take for granted in these other languages.

+2
source

Because if a variable has a static storage space, this initial value is undefined. You cannot rely on the fact that this is nothing, since the standard does not define it. However, even statically assigned variables must be initialized. Just initialize your variables and avoid potential headaches in the future. There is no good reason not to initialize a variable; there are many good reasons to do the opposite.

On the side note, do not trust a single book that claims to have taught you the X programming language in 21 days. They lie, get themselves a decent book.

+8
source

In C, the value of an uninitialized variable is undefined. This means that you do not know its meaning and may differ depending on the platform and the compiler. The same applies to connections of type struct and union .

Why? Sometimes you do not need to initialize a variable, because you are going to pass it to a function that fills it, and it does not care about what is in the variable. You do not need the initialization overhead imposed on you.

How? Primitive types can be initialized from literals or function return values.

 int i = 0; int j = foo(); 

Structures can be initialized with zeros with the aggregate syntax syntax:

 struct Foo { int i; int j; } struct Foo f = {0}; 
+1
source

Ultimately, you can use a variable declared outside the scope of your current method.

Consider the following

 int count = 0; while(count < 500) { doFunction(); count ++; } ... void doFunction() { count = sizeof(someString); print(count); } 
+1
source

In C, using values ​​of uninitialized automatic variables (non-static locales and variable parameters) that satisfy the requirement of being a register variable is undefined behavior, since such variable values ​​can be obtained from the register and some platforms can interrupt your program if you read such uninitialized values . This includes variables of type unsigned char (this was added to a later version of C to host these platforms).

Using the values ​​of uninitialized automatic variables that do not satisfy the requirement of being a register variable, like variables that have their own addresses, is fine until the C implementation you use has got traps for the variable type you are using. For example, if the variable type is unsigned char , the Standard requires that all platforms do not have trap representations stored in such variables, and reading an undefined value from it will always succeed and will not be undefined. Types such as int or short do not have such guarantees, so your program may crash depending on the C implementation you use.

Static storage duration variables are always initialized unless you do this explicitly, so you need not worry here.

For variables with allocated storage duration ( malloc ...), the same applies to automatic variables that do not satisfy the requirements for the register variable, since in these cases the involved C implementations must make your program read from memory and not run into problems in which reading in the register may cause exceptions.

+1
source

At the risk of being pedantic, the statement

DO NOT use a variable that has not been initialized.

wrong. If it were better expressed:

Do not use the value of an uninitialized variable.

The language distinguishes between initialization and purpose, so the first warning in this sense is more cautious - you do not need to provide an initializer for each variable, but you must either assign or initialize the variable with a useful and significant cost until you perform any operations that subsequently use its value.

So everything is fine:

 int i ; // uninitialised variable i = some_function() ; // variable is "used" in left of assignment expression. some_other_function( i ) ; // value of variable is used 

although the some_function () function called i not initialized. If you assign a variable, you definitely "use" it (to preserve the return value in this case); the fact that it is not initialized does not matter because you are not using its value.

Now if you stick

Do not use the value of an uninitialized variable.

as I suggested, the reason for this requirement becomes obvious - why do you accept the value of a variable without knowing that it contains something meaningful? Then the question may arise: β€œwhy does C not initialize auto variables with a known value. Possible answers to this would be:

  • Any arbitrary value provided by the compiler should not be significant in the context of the application β€” or, even worse, it may have a value that contradicts the actual state of the application.

  • C was deliberately designed to not have hidden utility resources due to its roots as a system programming language. Initialization is performed only with explicit encoding, since additional machine instructions and CPU cycles are required to execute.

Note that static variables are always initialized to zero. .NET languages, such as C #, have the concept of a null value or a variable that does not contain anything and that can be explicitly tested and even assigned. A variable in C cannot contain anything, but what it contains can be undefined, and therefore the code that uses its value will behave non-deterministically.

+1
source

All Articles