In C, how do you declare the members of a structur

2019-04-18 07:04发布

问题:

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

回答1:

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.



回答2:

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.



回答3:

I need to clarify volatile for C/C++ because there was a wrong answer here. I've been programming microcontroleurs since 1994 where this keyword is very useful and needed often.

volatile will never break your code, it is never risky to use it. The keyword will basically make sure the variable is not optimized by the compiler. The worst that shold happen if you overuse this keyword is that your program will be a bit bigger and slower.

Here is when you NEED this keyword for a variable : - You have a variable that is written to inside an interrupt function. AND - This same variable is read or written to outside interrupt functions. OR If you have 2 interrupt functions of different priority that use the variable, then you should also use 'volatile'.

Otherwise, the keyword is not needed.

As for hardware registers, they should be treated as volatile even without the keyword if you don't do weird stuff in your program.