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;
}
  1. ACode that always keeps the comparison so it returns 0 only when x is the maximum value
  2. BCode that always returns 1
  3. 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.
Practice this topic Back to topic

More Compilers questions

  1. Which program error can be detected at compile time?
  2. What is the main benefit of compile-time type checking in a statically typed language?
  3. What is commonly used to express the rules for recognizing tokens in lexical analysis?
  4. Which kind of grammar is used to describe most programming languages and underlies parsing?
  5. What does the abstract syntax tree for the expression 2 + 3 * 4 look like?