Issue
#include <stdio.h>
int print1(void)
{
static int x= 10;
x+=5;
return x;
}
int print2(void)
{
static int x;
x = 10;
x+= 5;
return x;
}
int main()
{
int x;
x = print1();
x+= print1();
x+= print2();
x+= print2();
printf("%d", x);
return 0;
}
My solution:
- First in print1 statement the value of the will increment by 5 , x will be 15 .
- Then upon calling print1 function for the 2nd time it will be 15+5=20, since it will hold the previous value.
- Now for the function print2, it will again initialise the x value with 10, then increment it by 5. Value of x will be 15.
- for the last statement value of x will be 15+5=20.
- x=15+20+15+20=70
But the answer is 65. Please correct me where did I go wrong? I even wrote it in my compiler, it is giving output 65, but if change the position of x inside Print2 statement like static int x=10, it is giving different output?
Why this is happening?
Solution
The init of a static variable like static int x=10;
only happens once per program execution. And that is not like a statement being executed, it is during setup of variables for the program.
The assignment statement x = 10;
is executed each time the function is executed.
This means the two code versions you discuss are different and especially have different effects on variable values; which in turn explains the different output.
Answered By - Yunnosch Answer Checked By - Mary Flores (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.