Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does making a struct volatile make all its members volatile?

Tags:

c++

If I have:

struct whatever {
int data;
};
volatile whatever test;
will test.data be volatile too?
like image 882
Mark Avatar asked Dec 18 '10 19:12

Mark


People also ask

Can a struct member be volatile?

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.

What is a volatile struct?

The volatile structure is a member of a non-volatile structure, a pointer to which is used to access a register.

Which variables are volatile?

A volatile variable is a variable that is marked or cast with the keyword "volatile" so that it is established that the variable can be changed by some outside factor, such as the operating system or other software.

What does volatile do?

volatile is a qualifier that is applied to a variable when it is declared. It tells the compiler that the value of the variable may change at any time-without any action being taken by the code the compiler finds nearby.


1 Answers

Another question can be asked (or simply another way to look at the original question):

Does making a struct const make all its members const?

If I have:

struct whatever { int data; };

const whatever test;

Will test.data be const too?

My answer is : Yes. If you declare an object of type whatever with const then all its members will be const too

Similarly, if you declare an object of type whatever with volatile then all its members will be volatile too, just like if you declare the object with const, all it's member will be const too.

const and volatile are two faces of the same coin; they're so that the Standard often refers to them as cv-qualifiers.


Quoting from the Standard ($7.1.5.1/8)

[Note: volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation. See 1.9 for detailed semantics. In general, the semantics of volatile are intended to be the same in C + + as they are in C. ]

That means, if your object is an instance of a struct, then the compiler cannot avoid aggressive optimization involving the object, unless it avoids aggressive optimization of each of it's members. (Otherwise, how else it can avoid optimization involving the object?)


Related topic:

Why do we use volatile keyword in C++?

like image 133
Nawaz Avatar answered Sep 29 '22 02:09

Nawaz