Let’s understand the code line by line:
1. In the main()
function, the fun()
function is called for the first time. Therefore, the control will transfer to the fun()
function.
2. Inside the fun()
function, two variables are defined: x with the initial value of 10, and y with the initial value of 20 (since y is a static variable, it retains its value even after the function execution).
3. The printf()
function is called to display the values of x and y on the screen, which are currently 10 and 20 respectively. This means that at this point, the output is 10 and 20.
4. The values of x and y are then incremented by 10, so x becomes 20 and y becomes 30.
5. The function execution of fun()
is completed, and the control returns to the caller, which is the main()
function. At this point, the variable x is destroyed because it is an automatic variable and only exists within the function’s execution. However, y remains in the memory with its value of 30 since it is a static variable.
6. The next line in the main()
function calls fun()
again. This transfers the control back to the fun() function.
7. This time, only x is defined and initialized with a value of 10, while y retains its value of 30 from the previous execution.
8. The printf()
function is called again to print the values of x and y, which are now 10 and 30 respectively.
9. Therefore, the overall output of the program is 10, 20, 10, 30.
10. Finally, since there are no more statements to execute in the main()
function, the program terminates.
So, the final output of the program is: 10, 20, 10, 30.
Leave a comment