ProgrammingHardIBM · Deloitte pattern
What happens? (Signed integer overflow.)
What happens? (Signed integer overflow.)
#include <limits.h>
int main(void) {
int x = INT_MAX;
int y = x + 1;
printf("%d", y);
}- A. Undefined behaviour: signed integer overflow is explicitly undefined in C, unlike unsigned overflow which wraps predictably
- B. It always triggers a compiler error
- C. It always prints 0
- D. It always wraps to INT_MIN (-2147483648), guaranteed by the standard
Correct answer: A. Undefined behaviour: signed integer overflow is explicitly undefined in C, unlike unsigned overflow which wraps predictably
Unlike unsigned integer arithmetic (which is guaranteed to wrap modulo 2^n), signed integer overflow is undefined behaviour per the C standard. In practice, many compilers with common optimisation settings do produce wraparound to INT_MIN, but the standard does not guarantee this, and aggressive optimizers may exploit the UB in surprising ways (e.g. assuming x+1 > x always).
More C Programming questions
- What happens? c int p = malloc(sizeof(int)); p = 10; free(p); printf("%d", p);
- What happens? c int divide(int a, int b) { return a / b; } int main(void) { printf("%d", divide(10, 0)); }
- What is printed? c #define DEBUG 0 int main(void) { #if DEBUG printf("debug moden"); #else printf("release moden"); #endif return 0; }
- Two files are compiled and linked together. What happens? c / file1.c / static int counter = 0; void inc(void) { counter++; } / file2.c /…
- What is printed? c int x = 10; void f(void) { int x = 20; { int x = 30; printf("%d ", x); } printf("%d ", x); } int main(void) { f()…
- What is printed? c void f(void) { register int i; int p = &i; p = 5; printf("%d", i); }