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:

  1. int m = 10;: Initializes m = 10.
  2. n = ++m;: Prefix increment increments m first (m=11m = 11), then assigns to n (n=11n = 11).
  3. n1 = m++;: Postfix increment assigns current value of m (11) to n1 (n1=11n1 = 11), then increments m (m=12m = 12).
  4. n--;: Postfix decrement decrements n from 11 to 10 (n=10n = 10).
  5. --n1;: Prefix decrement decrements n1 from 11 to 10 (n1=10n1 = 10).
  6. n -= n1;: Computes n=n−n1=10−10=0n = n - n1 = 10 - 10 = 0 (n=0n = 0).
  7. printf("%d", n);: Prints the final value of n, 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.