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:
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 namedx, so any reference toxinsideQrefers to the globalx. - Function
P(int *y): Declares a local variableint x. Any reference toxinsidePrefers to this localx. The pointerypoints to the variable passed frommain(which is the globalx).
2. Step-by-Step Execution Trace
Step 1: Execution starts in main()
x = 5;→ The global variablexis initialized to .P(&x);→ FunctionPis called with the address of the global variablex. Thus, insideP, the pointerypoints to the globalx(i.e.,*yis the globalx).
Step 2: Inside P(int *y)
int x = *y + 2;→ A local variablexis created. Since*yis the globalx(which is ), localxbecomes .Q(x);→ Calls functionQwith the value of localx() as the argument.
Step 3: Inside Q(int z) with z = 7
z += x;→ Since there is no localxinQ, it uses the globalx(which is still ). Thus,zbecomes .print(z);→ Prints12.
Step 4: Returning to P
*y = x - 1;→ Updates the value pointed to byy(which is the globalx). The localxis , so globalxbecomes .print(x);→ Prints the localx, which is7.
Step 5: Returning to main()
print(x);→ Prints the globalx, which is now6.
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.
