C Programming Basics

int and unsigned int are 32 bits. Which of the following is undefined behavior according to the C standard?

  1. AAdding 1 to an unsigned int variable whose value is the maximum 4294967295
  2. BShifting a negative int value right by 1 bit with >>
  3. 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.
Practice this topic Back to topic

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More C Programming Basics questions

  1. When the function above is compiled with gcc with optimization enabled, the check if (p == NULL) may be removed. Which of the following is the reason?
  2. Which of the following is what the C standard specifies about the size of the int type?
  3. In embedded programs, variables that hold the value of a 32-bit peripheral register are often declared with uint32_t from stdint.h rather than unsigned int. Which of the following is the main reason?
  4. Which of the following is the output when the code above, which includes a division of integers, is executed?
  5. Which of the following is the output when the code above, which uses prefix and postfix ++, is executed?