Skip to content
Official PYQ · 2003

GATE CS 2003 Q89 — Programming in C

Explain with AI

Consider the C program shown below:

#include<stdio.h>
#define print(x) printf("%d", x)

int x;
void Q(int z)
{
        z+=x;
        print(z);
}

void P(int *y)
{
        int x = *y + 2;
        Q(x);
        *y = x - 1;
        print(x);
}
main(void) {
        x = 5;
        P(&x);
        print(x);
}

The output of this program is:

Choose one option
View worked solution

Answer: A

To find the output of the program, we need to carefully trace the scope of the variable x (global vs. local) and the parameter passing.

1. Variable Scopes

  • Global Scope: int x; is declared globally.
  • Function Q(int z): Has no local variable named x, so any reference to x inside Q refers to the global x.
  • Function P(int *y): Declares a local variable int x. Any reference to x inside P refers to this local x. The pointer y points to the variable passed from main (which is the global x).

2. Step-by-Step Execution Trace

Step 1: Execution starts in main()

  • x = 5; → The global variable x is initialized to 55.
  • P(&x); → Function P is called with the address of the global variable x. Thus, inside P, the pointer y points to the global x (i.e., *y is the global x).

Step 2: Inside P(int *y)

  • int x = *y + 2; → A local variable x is created. Since *y is the global x (which is 55), local x becomes 5+2=75 + 2 = 7.
  • Q(x); → Calls function Q with the value of local x (77) as the argument.

Step 3: Inside Q(int z) with z = 7

  • z += x; → Since there is no local x in Q, it uses the global x (which is still 55). Thus, z becomes 7+5=127 + 5 = 12.
  • print(z); → Prints 12.

Step 4: Returning to P

  • *y = x - 1; → Updates the value pointed to by y (which is the global x). The local x is 77, so global x becomes 7−1=67 - 1 = 6.
  • print(x); → Prints the local x, which is 7.

Step 5: Returning to main()

  • print(x); → Prints the global x, which is now 6.

Conclusion

The sequence of printed values is 12 7 6, which corresponds to Option A.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions