Question
Consider the following C program.
#include <stdio.h>
int main() {
int m = 10;
int n, n1;
n = ++m;
n1 = m++;
n--;
--n1;
n -= n1;
printf("%d", n);
return 0;
}
The output of the program is
Official answer and solution
- Official answer
- 0
- From
- Official GATE 2017 answer key
Solution
Trace the prefix and postfix increment and decrement operations on variables m, n, and n1 step by step.
Trace line by line:
int m = 10;: Initializesm = 10.n = ++m;: Prefix increment incrementsmfirst (), then assigns ton().n1 = m++;: Postfix increment assigns current value ofm(11) ton1(), then incrementsm().n--;: Postfix decrement decrementsnfrom 11 to 10 ().--n1;: Prefix decrement decrementsn1from 11 to 10 ().n -= n1;: Computes ().printf("%d", n);: Prints the final value ofn, which is 0.
Final answer
0
Common trap
Mixing up prefix and postfix increments on m when assigning to n and n1.
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2017 Computer Science and Information Technology (CS) Session 2
- Question
- 54 of 65, printed as CS Q.54
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.