ProgrammingHardProduct-company MCQ pattern
What is printed?
What is printed?
int a = 1;
int b = a++ + a++;
int c = ++a + ++a;
printf("UB UB");- A. Both b and c are computed with well-defined, predictable values
- B. b's computation is undefined behaviour, but c's is well-defined
- C. Both b's and c's computations are undefined behaviour: each modifies a twice with no sequence point separating the modifications
- D. c's computation is undefined behaviour, but b's is well-defined
Correct answer: C. Both b's and c's computations are undefined behaviour: each modifies a twice with no sequence point separating the modifications
Both a++ + a++ and ++a + ++a modify the same variable a twice within a single expression, with + providing no sequencing guarantee between evaluating its two operands. Both expressions are undefined behaviour in C, regardless of whether one 'looks safer' than the other.
More C Programming questions
- What is printed? c int a = 5; int b = 10; int result = a > b ? a : b > 0 ? b : 0; printf("%d", result);
- What is printed? c int x = 5; int y = (x = 10) + (x = 20); printf("%d", y);
- What is printed? c int a = 1, b = 2; int result = !a == !b; printf("%d", result);
- What is printed? c int x = 10; int y = x > 5 ? x > 8 ? 1 : 2 : 3; printf("%d", y);
- What is printed? c int i = 0; int arr[5] = {10, 20, 30, 40, 50}; while (i < 5) printf("%d ", arr[i++]); printf("%d", i);
- What is printed? c int a = 5; int b = (a > 3) ? (a = 10) : (a = 20); printf("%d %d", a, b);