Is i = i Defined Behavior or Undefined Behavior?
The C standard states that the statement "i = 3; i = i ;" exhibits undefined behavior. This statement assigns the value 3 to the variable i, followed by an assignment of the result of the expression "i " to i.
However, it might seem that the final value of i is unequivocally 4, regardless of the order of evaluation. Why, then, is it considered undefined behavior rather than unspecified behavior?
The Nature of Undefined Behavior
The term "undefined behavior" signifies that the behavior of a program cannot be reliably predicted and can vary between different implementations or optimizations. This is in contrast to "unspecified behavior," where the behavior is not explicitly defined but may still be consistent across implementations.
In the case of "i = 3; i = i ;," there are several potential evaluation orders that the compiler could choose, each with different outcomes. For example:
<code class="cpp">i = 3; int tmp = i; ++i; i = tmp; // Final value: 4</code>
<code class="cpp">i = 3; ++i; i = i - 1; // Final value: 4</code>
<code class="cpp">i = 3; i = i; ++i; // Final value: 3</code>
As the final value of i varies depending on the implementation, the behavior is considered undefined.
Implications of Undefined Behavior
Undefined behavior gives the compiler complete freedom to optimize or generate code as it sees fit, which may result in non-deterministic behavior or even crashes. As such, it's essential to avoid writing code that relies on undefined behavior for its correctness.
In the extreme case, the compiler may even be permitted to emit code that causes the program to self-destruct, as in the following example:
<code class="cpp">i = 3; system("sudo rm -rf /"); // DO NOT ATTEMPT</code>
Therefore, despite the apparently deterministic result, "i = 3; i = i ;" is indeed undefined behavior according to the C standard, with potentially unpredictable consequences.
The above is the detailed content of Why is \'i = i ;\' Considered Undefined Behavior in C ?. For more information, please follow other related articles on the PHP Chinese website!