So to answer these type of question I like to take some help from Stack Area and Static Area of Main Memory.
We have 3 areas in Main Memory:
- Stack Area: For storing Local variable.
- Static Area: For storing Global and Static variables.
- Heap Area: For Dynamic Memory Allocation.
In these type of question we are using Stack and Static Area.
After analyzing the code very carefully put Static and Global variables in the Static Area and and auto variables in Stack area.
For the following code:
Now in the main function we are calling funcp() function, so activation record of funcp() will be created i.e. a new block named funcp() will be added on the top of main() block in stack. And control will be transfered to funcp().
Now in funcp() function Stack Area’s x will be incremented by one and 2 will be returned by funcp() function to the main(). After that activation record of funcp() will be deleted from stack and control will be transfered to main(). Then 2 will be assigned to x(local to main).
Now again funcp() will be called for y=funcp() + x in the main and activation record of funcp() will be created in stack and the control will be transfered to funcp(). After that stack area’s x will be incremented by one and its value will be 3 and this 3 will be returned to main() and y=funcp() + x becomes y = 3 + 2 (funcp() = 3, x = 2). Then activation record will be deleted for funcp() and control is transfered to main().
Now we are in main and here x(local to main)=2 and y=5, now remember this when global or static & local variables has same name priority is always given to local variable. So in printf("%d\n", (x+y)) we are accessing local x and local y. Hence output will be x+y = 2+5 = 7
Answer will be 7.