Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
970 views
in Technique[技术] by (71.8m points)

c - unused volatile variable

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...