The volatile keyword

Posted on 2009/03/03

2


The volatile keyword is a feature of the C language that is not considered by new developers until they bang their head against an apparently correct code that doesn’t work, and they don’t understand why. I think it is important to know the existence of the keyword and the principles behind it in order to have a chance to remember it in situations where you feel stuck.
A useful explanation of the details of the volatile keyword is of course in its Wikipedia entry; this is the brief description:

A variable or object declared with the volatile keyword may be modified externally from the declaring object.

I think that an analogy helps novice C developers as well:
A non-volatile variable is like a bowl of candies inside your drawer.
A volatile variable is like a bowl of candies on a table in the school hall.
If you put candies in a bowl in the hall, you can’t be sure that when you turn your back on the candies they will remain there. On the contrary, you are quite sure that the number of candies won’t be the same. The bowl of candies inside your drawer, however, is safe because only you can eat those candies; when you’re hungry, you can count on your personal candies, and you can’t count on the candies in the hall. When you forget to declare as “volatile” a variable that should be so, it’s like having a bowl of candies in the hall and saying “when I’m hungry, I’ll go eat those candies”: when you reach the empty bowl, you’ll recognize your mistake.

The current C standard ISO/IEC 9899:1999 contains the rigorous and non-obvious characteristics of the volatile keyword.

add to del.icio.us :: Bookmark Post in Technorati :: Add to Blinkslist :: add to furl :: Digg it :: add to ma.gnolia :: Stumble It! :: add to simpy :: seed the vine :: :: :: TailRank :: post to facebook :: Bookmark on Google :: Add to Netscape :: Share on Yahoo :: Add this to Live

Posted in: Software