C Programming Basics
int and unsigned int are 32 bits. Which of the following is undefined behavior according to the C standard?
- AAdding 1 to an unsigned int variable whose value is the maximum 4294967295
- BShifting a negative int value right by 1 bit with >>
- CAdding 1 to an int variable whose value is the maximum 2147483647
Show answer and explanation
Answer: C. Adding 1 to an int variable whose value is the maximum 2147483647
A signed integer operation whose result exceeds the representable range, such as 2147483647 + 1 in int, is undefined behavior. Unsigned integer arithmetic is defined to wrap modulo 2³², so 4294967295 + 1 gives 0 and is not undefined behavior. Right-shifting a negative value is implementation-defined behavior, where the implementation decides whether it is an arithmetic or a logical shift; gcc uses an arithmetic shift. On the other hand, left-shifting a negative value is undefined behavior.
- A. Unsigned arithmetic is defined to wrap back toward 0 on overflow, and the result is 0.
- B. Right-shifting a negative value is implementation-defined, not undefined behavior.
- C. Correct. Signed integer overflow is undefined behavior.