Reputation: 33
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.
Upvotes: 3
Views: 2010
Reputation: 753495
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.
Upvotes: 7
Reputation: 16406
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.
Upvotes: 3
Reputation: 935
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.
Upvotes: -1