Reputation:
What is the difference in volatile in c# and c? I was asked this in one interview.
Upvotes: 12
Views: 1214
Reputation: 5705
The article mentioned in this blog post by Herb Sutter explains the things concisely and clearly and compares the usage and meaning of volatile in C, C++, Java and C#.
There are a couple of good questions and answers on this very site also:
EDIT: to not confuse anyone here is the "exact link" to the DDJ article mentioned in the initial link(which is a link to Herb Sutter's blog).
Also this article by Nigel Jones explains the volatile keyword in the context of embedded C programming. As this question seems to have popped up in an interview this other article by the same author is one of my favorites("exact link") and has another good explanation of volatile in the C world.
Upvotes: 16
Reputation: 1653
In C volatile tells the compiler not to optimize access to a variable:
int running = 1;
void run() {
while (running) {
// Do something, but 'running' is not used at all within the loop.
}
}
Normally the compiler may translate 'while (running)' in this case to just 'while (1)'. When the 'running' variable is marked as volatile, the compiler is forced to check the variable each time.
Important is to understand that for C 'volatile' only restricts the compiler to optimize, while your hardware (i.e. the CPU caches, instruction pipeline, etc) may still reorder memory access. There is no way your C compiler will tell your hardware not to optimize. You have to do it yourself (e.g. by using a memory barrier).
As far as I know (but I'm not completely sure) the C# specification takes this a bit further:
Upvotes: 2