ProgrammingHardWipro · Cognizant pattern

What is printed? (Integer overflow on multiplication.)

What is printed? (Integer overflow on multiplication.)
#include <limits.h>
int main(void) {
    int a = INT_MAX;
    int b = 2;
    int result = a * b;
    printf("overflow-checked");
    printf("%d", result);
}
  1. A. It is undefined behaviour: a*b overflows signed int range (INT_MAX*2 far exceeds INT_MAX), so no portably guaranteed numeric result exists for `result`
  2. B. It prints -2
  3. C. It prints 4294967294
  4. D. It always triggers a runtime trap with a defined error message

Correct answer: A. It is undefined behaviour: a*b overflows signed int range (INT_MAX*2 far exceeds INT_MAX), so no portably guaranteed numeric result exists for `result`

INT_MAX * 2 vastly exceeds the representable range of a signed int; signed overflow is undefined behaviour in C (unlike unsigned, which wraps predictably) — the actual bit pattern a compiler happens to produce (often resembling -2 under typical two's-complement wraparound, but not guaranteed, especially with optimisations enabled) cannot be relied upon.

More C Programming questions

Exams that ask this topic