Does making a struct volatile make all its members volatile?

C++

C++ Problem Overview


If I have:

struct whatever {
int data;
};

volatile whatever test;
will test.data be volatile too?

C++ Solutions


Solution 1 - C++

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:

https://stackoverflow.com/questions/4437527/why-do-we-use-volatile-keyword-in-c/4437555#4437555

Solution 2 - C++

From: http://msdn.microsoft.com/en-us/library/145yc477%28v=vs.80%29.aspx

To declare the object pointed to by the pointer as const or volatile, use a declaration of the form:

const char *cpch;
volatile char *vpch;

To declare the value of the pointer — that is, the actual address stored in the pointer — as const or volatile, use a declaration of the form:

char * const pchc;
char * volatile pchv;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarkView Question on Stackoverflow
Solution 1 - C++NawazView Answer on Stackoverflow
Solution 2 - C++Virtually RealView Answer on Stackoverflow