ProgrammingHardIBM · Deloitte pattern
Assume 32-bit int. What is printed?
Assume 32-bit int. What is printed?
unsigned int a = 5;
int b = -3;
printf("%d", a + b > 0);- A. 1
- B. 0
- C. Compile-time error: cannot mix signed and unsigned in addition
- D. Undefined behaviour
Correct answer: A. 1
When an unsigned int and a signed int are combined in arithmetic, the signed operand is converted to unsigned (the usual arithmetic conversions). b=-3 becomes a huge unsigned value (2^32 - 3) when converted; adding that to a=5 wraps around (modulo 2^32) back to 5 + (2^32-3) mod 2^32 = 2, which as an unsigned value is 2, clearly > 0, printing 1 — this happens to work out numerically correctly here (matching the expected -3+5=2), though the TYPE of the comparison is unsigned the whole way through.
More C Programming questions
- Assume 32-bit int. What is printed? c int x = 3; int y = 1 << x | 1; printf("%d", y);
- Assume 32-bit int. What is printed? c int permissions = 0; #define READ 4 #define WRITE 2 #define EXEC 1 permissions |= READ | WRITE…
- What happens when this runs? c int main(void) { int arr[3]; for (int i = 0; i < 3; i++) { printf("%d ", arr[i]); } }
- What happens when this runs? c void f(int p) { free(p); p = 10; } int main(void) { int x = malloc(sizeof(int)); f(x); printf("done"); }
- What happens when this runs? c int compute(int a, int b) { int result; if (a > b) { result = a - b; } return result; } int main(void) {…
- What happens when this runs? c int makeArray(void) { int local[10]; for (int i = 0; i < 10; i++) local[i] = i; return local; } int…