Uninitialized Variable Self-Initialization: Perils and Standards
The C/C code snippet below:
int i = i;
has raised concerns among developers, as it uses an uninitialized variable to initialize itself. Modern compilers accept this code without warnings, raising questions about its legality and the underlying behavior defined by the standards.
Compiler Acceptance and Standards
According to the C11 standard, an uninitialized variable has an indeterminate value, which can be an unspecified value or a trap representation. In situations where the indeterminate value happens to be a trap value, using it can lead to undefined behavior if the implementation supports padding bits in integers.
However, if the implementation does not use padding, the value is unspecified, and there is no undefined behavior.
The Undefined Scenario
The behavior of using an uninitialized variable for self-initialization becomes even more unpredictable if the variable's address is never taken. Section 6.3.2.1p2 of the C11 standard clarifies that such usage is undefined for objects of automatic storage duration that could have been declared with the register storage class.
Implications
Despite compiler acceptance, using uninitialized variables for self-initialization is not recommended practice. It can lead to erroneous behavior or potential undefined behavior depending on the implementation, making the code unreliable. Always initialize variables explicitly to avoid these pitfalls.
The above is the detailed content of Is Self-Initialization of Uninitialized Variables in C/C Undefined Behavior?. For more information, please follow other related articles on the PHP Chinese website!