Should infinite loop condition variables always be

2019-06-12 14:39发布

问题:

Consider, such type of code,

while( !cond )
 ;

If cond is not declared volatile, the compiler can optimize it by caching it in a register. In that case, the while loop will continue even after cond is set.

Now does that mean that any such kind of variable should always be declared volatile? Why aren't the compilers smart enough to realize that it should not cache such variables?

回答1:

Why would it not cache the variable? You don't change it in the loop, so it's equivalent, in C's mind, to while (true);.

That is, unless your program is multithreaded, in which case the variable can be changed while the loop is running and doing nothing. However, the C language doesn't know anything about threads (and more generally, as Lundin remarked, about any functions that aren't called from main or from a function called in main, etc), so you have to use volatile by yourself to let C know that something is going on that it doesn't know about.