The integer value printed by the ANSI-C program given below is ________.…
2023
The integer value printed by the ANSI-C program given below is ________.
#include<stdio.h>
int funcp(){
static int x = 1;
x++;
return x;
}
int main(){
int x,y;
x = funcp();
y = funcp()+x;
printf("%d\n", (x+y));
return 0;
}
Attempted by 108 students.
Show answer & explanation
Correct answer: 7
Answer: 7
Key point: The local variable declared with the static keyword is initialized once and retains its value across function calls.
The static variable is initialized to 1 before any calls.
First call to the function increments the static variable from 1 to 2 and returns 2. This value is stored in the main function's x (so main x = 2).
Second call to the function increments the static variable from 2 to 3 and returns 3. That return value is added to the main x (which is 2), so y = 3 + 2 = 5.
Finally, the program prints x + y = 2 + 5 = 7.