Behavior of Uninitialized Variable Used as Its Own Initializer
This code in C/C raises questions about its behavior:
int i = i;
Despite the presence of an uninitialized variable, this code compiles without warnings and errors. Why does this happen, and what does the standard say about its behavior?
Indeterminate Value and Implementation Dependence
When a variable like i is used to initialize itself, it contains an indeterminate value. This value can either be an unspecified value or a trap representation. An unspecified value is not defined by the standard and is implementation-dependent. A trap representation, if supported by the implementation, triggers undefined behavior when used.
Undefined Behavior with Padding
If the implementation allocates padding bits in integer types, and if the indeterminate value is a trap representation, then using it results in undefined behavior. This is because accessing the trap representation causes unexpected results.
Unspecified Value without Padding
However, if the implementation does not allocate padding bits in integers, the indeterminate value is simply unspecified. In this case, there is no undefined behavior, and the exact value of i is determined by the implementation.
Undefined Behavior with Address Taken
Additionally, the behavior can become undefined even if i does not have its address taken, as stated in the C11 standard:
"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, the behavior is undefined."
Therefore, the behavior of this code is implementation-dependent and can be undefined depending on various factors.
The above is the detailed content of Why Does `int i = i;` Compile with Undefined Behavior?. For more information, please follow other related articles on the PHP Chinese website!