About the following code:
#include <stdio.h>
int lastval(void)
{
`static int k = 0;
return k++;
}
int main(void)
{
int i = 0;
printf("I previously said %d\n", lastval());
i++;
i++;
i++;
i++;
i++;
printf("I previously said %d\n", lastval());
i++;
i++;
i++;
printf("I previously said %d\n", lastval());
i++;
i++;
i++;
printf("I previously said %d", lastval());
i++;
i++;
i++;
return 0;
}
can anyone explain to me how does static maintain its value ? I though it was because the stack frame for the function wasnt destroyed after the return so I wrote this code to run it under gdb and I after doing backtraces after every single line only main's stack frame show up (it doesnt even list lastval when I do a backtrace sitting on a printf call, but anyway).
How its k actually stored ? I know that's not like a normal variable since the first k++ returns 1 instead of 0, and its not like a global since i cant access k inside main for example, so .. what's going on ?
`on a local k, K++ // Always returns 0
`on a global k = 0, k++ // returns 0, 1, 2
`on a static k, k++ // returns 1, 2 ,3
Can anyone help me to understand these 2 issues ?