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.
Clifford
source share