ProgrammingVery hard

Which expression sets bit 31 of an unsigned 32-bit variable x with no undefined behaviour?

  1. A. x |= 1 << 31;
  2. B. x |= 1 << 32;
  3. C. x |= 1u << 31;
  4. D. x = 1 << 31 - 1;

Correct answer: C. x |= 1u << 31;

1u << 31 is an unsigned shift that stays within the type. 1 << 31 shifts into the sign bit of int, which is undefined.

More C Programming questions

Exams that ask this topic