In the realm of programming, it is often a point of concern to use uninitialized variables. However, in the case of an uninitialized variable being used as its own initializer, a unique scenario arises.
Consider the following code:
int main(void) { int i = i; }
Surprisingly, this code is It can be compiled with clang/gcc/clang /g using standards such as 11. Additionally, the compiler does not issue any warnings when you specify the -Wall -Wextra option.
However, if you change your code to int i = i 1; and specify the -Wall option, you may receive a warning similar to the following:
why.c:2:13: warning: variable 'i' is uninitialized when used within its own initialization [-Wuninitialized] int i = i + 1; ~ ^ 1 warning generated.
So why does the compiler allow this code? Also, how does the C/C standard specify this?
Compiler Tolerance
The variable i is uninitialized when it self-initializes, so it has a non-specific value at that point. A non-specific value is either unspecified value or trap expression.
If an implementation supports stuffing bits for integer types and non-specific values are trap expressions, using it will result in undefined behavior.
If the implementation does not have the integer padding bit, the value is simply unspecified and no undefined behavior occurs.
Standard Provisions
Section 6.3.2.1p2 of the C11 standard details:
lvalue represents an object with automatic storage duration, the object could have been declared with the register storage class (the address was never taken), and the object was uninitialized ( If it is not declared in an initializer and no assignment is performed before use), its behavior is undefined.
So if you have never obtained the address of i, you will get undefined behavior. Otherwise, the above statement applies.
The above is the detailed content of Why does the compiler allow self-initialization of variables in C/C ?. For more information, please follow other related articles on the PHP Chinese website!