If I have:
struct whatever {
int data;
};
volatile whatever test;
will test.data
be volatile too?
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.
The volatile structure is a member of a non-volatile structure, a pointer to which is used to access a register.
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.
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.
Another question can be asked (or simply another way to look at the original question):
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++?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With