unused volatile variable

依然范特西╮ 提交于 2019-12-18 09:11:23

问题


If i declare a variable as volatile and if I dont use it any where in the program, will the compiler optimize that variable ?

What in case of local and global declarations of volatile variables in this case?

tq.


回答1:


The compiler can, and probably will, eliminate (ignore) the unused volatile variable declaration (but the compiler cannot eliminate an unused global variable definition - it has to assume that some other translation unit (TU) will reference it).

If the variable is local to the function and unused, it can be eliminated by the compiler, regardless of its volatility. It is not clear you can have meaningful local volatile variables, though I suppose you could call a function that passes its address to some code that then arranges for an interrupt handler to write to that variable - achieving volatility (but it is then, clearly, a used variable).

The volatile qualifier controls (influences) how the compiler generates the code that accesses the variable - if the code does not access the variable, there is no need to alter the code that it generates except to avoid generating a reference to the variable. It may as well not exist.


Further thoughts:

If the variable is static volatile and unreferenced in the source code, can it be eliminated?

The answer is (almost certainly) yes. There is no reference to the variable in the source, and the only ways it can be accessed in a portable manner require it to be referenced. Possible unportable hacks would include having multiple such static variables defined, and passing a reference to one of them to some function, and that function then expects to be able to access the other variables by address manipulation. However, such code is at best gruesome and non-portable. The author of such should probably be taken out back somewhere and quietly dissuaded from writing such code again.

So, a global variable definition cannot be eliminated; it might be referenced from another TU. A static variable definition that is unused can be eliminated. A local variable definition that is unused can be eliminated. And this applies whether the variable in question has a volatile qualifier or not.




回答2:


volatile is irrelevant to storage allocation -- if the compiler eliminates an unused variable without the volatile keyword, it can and probably will eliminate it with the volatile keyword. If you want to know for sure, check the generated code or symbol table.




回答3:


If a variable is not used, that is the most optimum situation of all. Optimizations are done only in the case of operations and calculations.

If no operations are performed on the data, no optimization is needed.



来源:https://stackoverflow.com/questions/4933314/unused-volatile-variable

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