Hi all,
I was studying a code and came across a variable definition as :
static volatile int x;
can anybody help me understand its behaviour during runtime?
Thanks,
Edesign
Printable View
Hi all,
I was studying a code and came across a variable definition as :
static volatile int x;
can anybody help me understand its behaviour during runtime?
Thanks,
Edesign
static refers to the scope of the variable. If the variable is global, it means that the scope is limited to the source file it was declared in. If the variable is local to a function, then it means the memory used to hold this variable is in the application's statically allocated memory. An example of how this effects your program could be seen with:
Every time foo() is called, the value of x is increased. Try this in a program and compare the difference of when x is declared as static vs x being declared normally.Code:void foo(void)
{
static int x = 0;
x++;
printf("%d\n", x);
}
The volatile keyword is used to indicate that the compiler should not perform optimizations which cache the value of the variable. It forces the compiler to generate code which always goes to memory to read the value stored in the variable. This is useful if you know that the memory location that this variable is at may be modified outside the scope of your application. An example would be in embedded devices that use memory mapped registers.
@bithub
Thanks that was clear.