Initialization and lvalue-to-rvalue conversion
The provided code snippet raises a commonly debated issue in C . Initializing a variable with itself, as in int x = x;, involves an lvalue-to-rvalue conversion. The question arises whether this conversion leads to undefined behavior (UB) considering that the right-hand 'x' is an uninitialized value, and lvalue-to-rvalue conversion on uninitialized values is generally prohibited.
Evidence of Expected lvalue-to-rvalue Conversion
While the C 11 Standard lacks an explicit specification regarding value categories expected by language constructs, circumstantial evidence suggests that rvalues are intended to be the default expectation.
Application to Initializer Conversion
By analogy to the behavior of built-in operators, it is reasonable to assume that copy-initialization also expects a prvalue as an initializer. This assumption is further supported by the following:
Implications for the Code Snippet
Under the assumption that copy-initialization expects a prvalue, the code snippet int x = x; would indeed lead to UB. This is because the right-hand 'x' is an uninitialized lvalue, and its lvalue-to-rvalue conversion would result in an indeterminate value.
Further Evidence
A proposed defect report highlights the need to clarify that lvalue-to-rvalue conversion on objects with an indeterminate value causes UB. This proposed change further supports the notion that copy-initialization should not allow such conversions.
Conclusion
Based on the available evidence, it is most likely that int x = x; constitutes UB in C , as the lvalue-to-rvalue conversion on the uninitialized 'x' is prohibited. However, it is important to note that the Standard lacks a definitive specification on expected value categories, leaving some room for ongoing debate.
The above is the detailed content of Is `int x = x;` Undefined Behavior in C Due to Lvalue-to-Rvalue Conversion?. For more information, please follow other related articles on the PHP Chinese website!