Compilers
In C, signed integer overflow is undefined behavior. Under this rule, which code might an optimizing compiler generate for the function above?
int f(int x) {
return x + 1 > x;
}
- ACode that always keeps the comparison so it returns 0 only when x is the maximum value
- BCode that always returns 1
- CNothing; it stops compilation with an error because of the undefined behavior
Show answer and explanation
Answer: B. Code that always returns 1
Because signed overflow is undefined behavior, the compiler may assume a correct program never overflows. Under that assumption x + 1 is always greater than x, so the comparison can be dropped and the function can always return 1. Code expecting 0 when x is the maximum may then not behave as hoped. Undefined behavior is usually not detected at compile time and does not produce an error.
- A. Assuming no overflow, the comparison need not be kept.
- B. Correct. Assuming no overflow, the comparison is always true.
- C. Undefined behavior usually does not cause a compile-time error.