What is the output of the following C program? void main() { int k, val = 1; k…
2021
What is the output of the following C program?
void main()
{
int k, val = 1;
k = ++val * ++val;
printf("%d", k);
}- A.
1
- B.
4
- C.
9
- D.
16
Attempted by 463 students.
Show answer & explanation
Correct answer: C
Concept
Because the same variable val is modified twice in this one expression (between two sequence points), standard C does NOT define a single guaranteed result — the output is undefined and can vary by compiler. The conventional model used by legacy compilers such as Turbo C, which this DSSSB key follows, is: each prefix ++val increments val before its value is used, so by multiplication time both factors read the same latest value of val. Under that convention the program prints 9.
Application
Start:
val = 1.First
++valraisesvalfrom 1 to 2.Second
++valraisesvalfrom 2 to 3.Both factors now refer to
val, which holds 3, so the product is 3 × 3 = 9.Hence
k = 9andprintfprints 9.
Important caveat (why answers differ)
This expression modifies val twice between two sequence points, so the C standard leaves the result undefined: the compiler is free to print different values. Legacy academic compilers such as Turbo C apply both increments first and then multiply, giving 3 × 3 = 9; some modern optimising compilers may instead print 6 (2 × 3). For this DSSSB question the official key follows the Turbo C convention, so the expected answer is 9.
Cross-check
This confirms the result is self-consistent under the Turbo C / official-key convention: if both ++val operations complete before either factor of the multiplication is read, val finishes at 3 and 3 × 3 = 9. This is NOT an independent proof under the C standard — the two increments are unsequenced, so a compiler that reads one factor before applying the other operand's increment can legitimately print a different value (e.g. 6).