Question

The output of the following C program is _____.

#include <stdio.h>

void f1(int a, int b) {
    int c;
    c = a; a = b; b = c;
}

void f2(int *a, int *b) {
    int c;
    c = *a; *a = *b; *b = c;
}

int main() {
    int a = 4, b = 5, c = 6;
    f1(a, b);
    f2(&b, &c);
    printf("%d", c - a - b);
    return 0;
}
Official answer and solution
Official answer
-5
From
Official GATE 2015 answer key

Solution

Trace the C function calls, distinguishing between call-by-value and call-by-reference using pointers.

  1. In main(), variables are initialized: a = 4, b = 5, c = 6.
  2. Call f1(a, b):
    f1(int a, int b) receives arguments by value. The swaps within f1 affect only its local copies. On return, variables in main() remain unchanged: a = 4, b = 5, c = 6.
  3. Call f2(&b, &c):
    f2(int *a, int *b) receives the addresses of b and c from main():
    int c; // local variable in f2
    c = *a; // c = 5
    *a = *b; // *a (main's b) = 6
    *b = c;  // *b (main's c) = 5
    
    Thus, after f2(&b, &c), b becomes 66 and c becomes 55.
  4. Evaluate the printf expression c - a - b:
    Value=c−a−b=5−4−6=−5.\text{Value} = c - a - b = 5 - 4 - 6 = -5.

The output printed is -5.

Final answer

-5

Common trap

Assuming f1 modifies main's a and b, or miscalculating the arithmetic expression 5−4−65 - 4 - 6 as +5+5.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2015 Computer Science and Information Technology (CS) Session 1
Question
21 of 65, printed as CS Q.11
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.