ad3angel1s ad3angel1s - 9 months ago 42
C Question

Is a global implicitly volatile in C?

My question is very simple. The keyword volatile is mandated when you want to tell the compiler that variable could change outside of the scope where it's used, for example a memory mapped variable in an embedded system or a signal handler variable that can change in response to receiving a signal from the OS.
[Removed the part on thread communication as it's just generating confusion, that's not my question].
[Rephrasing the question to clarify using a comment below]

I think what the OP is asking, is whether volatile would add further restrictions that are not already imposed by the global nature of the variable (the fact that it's global places certain restrictions on the compiler that are similar to the restrictions that volatile mandates).

usr usr
Answer Source

Is a global implicitly volatile in C?


You are mixed up about the extern variables and volatile variables because they both can't be fully optimized by the compiler because they both can be modified externally. But that doesn't mean they have the same semantics.

Consider Link Time Optimzation which is possible for global variables. That means, it's entirely possible for a compiler to have complete information on a global variable and thus optimize it accordingly just like any other variable. But volatile means compiler just can't have any assumptions about it. Because it could be modified externally at run time.


volatile int vol_global_var;


int nonvol_global_var;

can't be treated as same. Because, with sufficient information, a compiler could completely optimize away nonvol_global_var. But it can never do that for vol_global_var.

So, when would you make a global variable volatile qualified is not different deciding when you'd want make any variable to be volatile qualified.