In C a variable of automatic storage class has initial value as garbage value. But the variable declared in the following way gives everytime 0 for all such variables, while it should be a garbage value.
auto int i;
printf("%d",i);
In C a variable of automatic storage class has initial value as garbage value. But the variable declared in the following way gives everytime 0 for all such variables, while it should be a garbage value.
auto int i;
printf("%d",i);
auto int i;
printf("%d",i);
The keyword auto
is unnecessary here; it specifies a storage class that is the default anyway.
The behavior of the above code is explicitly undefined. See N1570 6.3.2.1 paragraph 2. The wording is a bit dense, but it describes how an lvalue (basically an expression that designates an object) is "converted" to the value stored in the object -- in this case, the relevant object is i
.
If the lvalue designates an object of automatic storage duration that could have been declared with the
register
storage class (never had its address taken), and that object is uninitialized (not declared with an initializer and no assignment to it has been performed prior to use), the behavior is undefined.
The value stored in i
is arbitrary, and in practice retrieving that value is very likely to give you something that looks like an int
value, but the behavior of that access is undefined, which means that the standard says nothing about what actually happens. A compiler can reject the program altogether, or the output of the printf
call could in principle be a hyperintelligent shade of the color blue (the latter is admittedly unlikely).
If the access retrieves whatever value is stored in that chunk of memory, then 0
is as likely as any other value, perhaps more so. You might get a different value when you run the same program tomorrow.
(N1570 is the latest publicly available draft of the 2011 ISO C standard.)
As per C11 standard (as of N1570):
Section 6.7.9, verse 10
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.
Section 3.19.2
indeterminate value
either an unspecified value or a trap representation
Section 3.19.3
unspecified value
valid value of the relevant type where this International Standard imposes no requirements on which value is chosen in any instance
(This, with only minor changes, is the same wording as in the C99.)
In other words, it's up to compiler or chance what the value can be. It may so happen that the compiler you use imposes additional restrictions on the variables and defaults them to some value.