tags:

views:

423

answers:

4

How do you declare a particular member of a struct as volatile?

+5  A: 

Should be pretty straight forward according to this article:

Finally, if you apply volatile to a struct or union, the entire contents of the struct/union are volatile. If you don't want this behavior, you can apply the volatile qualifier to the individual members of the struct/union.

Olli
+13  A: 

Exactly the same as non-struct fields:

#include <stdio.h>
int main (int c, char *v[]) {
    struct _a {
        int a1;
        volatile int a2;
        int a3;
    } a;
    a.a1 = 1;
    a.a2 = 2;
    a.a3 = 3;
    return 0;
}

You can mark the entire struct as volatile by using "volatile struct _a {...}" but the method above is for individual fields.

paxdiablo
+1  A: 

Just a warning on the C/C++ volatile keyword.

Unless you know what you are doing you should never use it.

C/C++ volatile != java/C# volatile

volatile does not help in threaded code unless you really know what you are doing, you need to use C++0x atomic template (or something similar).

The only time I've had to use volatile is when controlling hardware registers.

Shane Powell
I think you've stated that a bit stronger than is strictly needed. volatile does help with threaded code, especially on single core embedded platforms. But you do have to know how to use it. It is also effectively mandatory when referencing hardware registers with or without DMA, especially a register that will be polled for status. It is also necessary to understand your cache and how to manage it correctly, and to understand how to do atomic operations on your platform.
RBerteig
You are right. I didn't know that I was thinking when I said DMA, I meant MMIO. I've edited the answer to something better (I hope).
Shane Powell
According to wikipedia ( http://en.wikipedia.org/wiki/Volatile_variable ), C# seems to have the same behavior as C/C++, while only Java has a different semantic.
Denilson Sá
The wiki page says: "Note that operations on a volatile variable in C and C++ are not guaranteed to be atomic." and that is the main difference between C/C++ and C#/Java. In C++0x you use the atomic template to make make a variable work in volatile in C#/Java.
Shane Powell
A: 

If the members declared as volatile are not changed due to servicing some interrupt (i.e. a signal handler or other (near) atomic variable), you should probably not be using volatile (as most compilers will optimize it away if its not near enough).

Otherwise, as others have said .. just use it then examine the asm dumps to see if your compiler actually agrees with you :)

In some cases, i.e. certain versions of gcc .. its worth checking those dumps.

Tim Post