Should infinite loop condition variables always be declared as volatile?

ぃ、小莉子 提交于 2020-01-03 04:48:26

问题


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.



来源:https://stackoverflow.com/questions/8989168/should-infinite-loop-condition-variables-always-be-declared-as-volatile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!