Alex Rivera | Logout

What is the difference between a static global and a static volatile variable?

Asked 2008-12-06T14:14:09.577
28

I have used a static global variable and a static volatile variable in file scope,

both are updated by an ISR and a main loop and main loop checks the value of the variable.

here during optimization neither the global variable nor the volatile variable are optimized. So instead of using a volatile variable a global variable solves the problem.

So is it good to use global variable instead of volatile?

Any specific reason to use static volatile??

Any example program would be appreciable.

Thanks in advance..

Edit
Report

1 Answer

14

The "volatile" keyword suggests the compiler not to do certain optimizations on code involving that variable; if you just use a global variable, nothing prevents the compiler to wrongly optimize your code.

Example:

#define MYPORT 0xDEADB33F

volatile char *portptr = (char*)MYPORT;
*portptr = 'A';
*portptr = 'B';

Without "volatile", the first write may be optimized out.

answered 2008-12-06T14:21:18.047

Your Answer