Unused volatile variable

If I declare a variable as volatile, and if I do not use it somewhere in the program, will the compiler optimize this variable?

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

TQ.

+2
source share
3 answers

The compiler can and will probably exclude (ignore) the unused declaration of the volatile variable (but the compiler cannot eliminate the unused definition of the global variable - it must assume that some other translation unit (TU) will refer to it).

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

The volatile qualifier controls (affects) how the compiler generates code that accesses the variable - if the code does not have access to the variable, there is no need to change the code that it generates, except to avoid creating a reference to the variable. It also cannot be.


Further thoughts:

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

The answer (almost certainly) is yes. There is no reference to a variable in the source, and the only ways that you can access it in portable mode require a reference to it. Possible unauthorized hacks include defining several of these static variables and passing a reference to one of them to some function, and this function then expects to be able to access other variables by manipulating addresses. However, such code is awful and non-portable at best. The author of this, probably, should be taken out somewhere and quietly dissuaded from writing such code again.

Thus, the definition of a global variable cannot be eliminated; other TUs may refer to it. A static definition of a variable that is not used can be eliminated. A local definition of a variable that is not used can be eliminated. And this applies to whether the variable in question has a volatile qualifier or not.

+6
source

volatile has nothing to do with storage allocation - if the compiler excludes an unused variable without the volatile keyword, it can and will probably eliminate it with the volatile keyword. If you want to know exactly, check the generated code or symbol table.

+3
source

If the variable is not used, this is the most optimal situation for everyone. Optimizations are performed only in the case of operations and calculations.

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

-1
source

Source: https://habr.com/ru/post/980644/


All Articles