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);
}- 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`
- B. It prints -2
- C. It prints 4294967294
- 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
- What happens? c int arr[3] = {1, 2, 3}; int p = arr; p += 10; p = 99; printf("done");
- What happens? c int compare(const void a, const void b) { return (int )a - (int )b; } int main(void) { int arr[] = {5, 2, 8, 1, 9}…
- Assume 32-bit int. What is printed? c unsigned int a = 0; a--; printf("%u", a);
- Assume 32-bit int. What is printed? c int flags = 0b1010; int mask = 0b0110; printf("%d %d", flags & mask, flags | mask);
- Assume 32-bit int. What is printed? c int x = 100; int y = x << 1; int z = x >> 1; printf("%d %d", y, z);
- Assume 32-bit int. What is printed? c int a = 12, b = 10; int x = a ^ b; int y = x ^ b; int z = x ^ a; printf("%d %d", y, z);