Hi,
I am following a C course on a book, that's good. Now I am studying the functions, the different type of variables, such as static, local and global variables.
There is in the chapter an example of how these types of variables behave when they are on a program, but I do not understand the static example.
Here the source code:
#include<stdio.h>
void useLocal(void);
void useStaticLocal(void);
void useGlobal(void);
int x = 1;
int main()
{
int x = 5;
printf("Local x in outer scope of main is %d\n", x);
{
int x = 7;
printf("Local x in inner scope of main is %d\n", x);
}
printf("Local x in outer scope of main is %d\n", x);
useLocal();
useStaticLocal();
useGlobal();
useLocal();
useStaticLocal();
useGlobal();
printf("\nlocal x in main is %d\n",x);
return 0;
}
void useLocal(void)
{
int x = 25;
printf("\nlocal in useLocal is %d after entering useLocal\n",x);
x++;
printf("\nlocal in useLocal is %d before exiting useLocal\n",x);
}
void useStaticLocal(void)
{
static int x = 50;
printf("\nlocal static x is %d on entering useStaticLocal\n",x);
x++;
printf("\nlocal static x is %d on exiting useStaticLocal\n",x);
}
void useGlobal(void)
{
printf("\nglobal x is %d on entering useGlobal\n",x);
x *= 10;
printf ("\nglobal x is %d on exiting useGlobal\n",x);
}
As you can see in the function useLocal the value of variable x is set to 25;at the first call, its value is still 25, then is incresead of 1, and when it's called another time,its value is 26. Ok, so far so good!!
Now have a look at the following function, namely useStaticLocal. The code is almost the same expect for the word "static" before int x. The out put of the first call is 51, and then is 52 on the second, but I am not understanding, why?
The increment is after the entering the function, so why is there an increment before the entering?
Is there anyone able to explain me the mechanism of how it works a static variable?
Thank You very much indeed
Bye bye
fab2