Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Volatile Type Quantifier Position In Variable Definition

I have been doing some research and haven't found a good answer and I am hoping for some better understanding. I know how to use volatile but have a question about what it does when its placement is different in variable declarations, for example.

  • volatile int * ptr;

The integer pointed to is volatile and when reading/writing to this memory location always go to the memory location.

  • int * volatile ptr;

The pointer value itself is volatile and when reading/writing to this memory location always go to the memory location.

It's a subtle difference, but from what I can tell the difference is something like this.

volatile int * foo;
int * volatile bar;
volatile int testInt = 5;
 ------------------------
|          0x020         | - 0x000 (foo), memory location 0x000 can be cached.
 ------------------------ 
|          0x020         | - 0x010 (bar), memory location 0x010 can't be cached.
 ------------------------
|           5            | - 0x020 (testInt)
 ------------------------

My question is what if the volatile quantifier isn't on a pointer type, for example.

volatile int foo = 5;
int volatile bar = 5;
 ------------------------
|            5           | - 0x000 (foo), memory location 0x000 can't be cached.
 ------------------------ 
|            5           | - 0x004 (bar), memory location 0x004 can't be cached.
 ------------------------

Don't these two declarations do the same thing for non-pointer declarations?

like image 609
RJN Avatar asked Oct 30 '22 02:10

RJN


1 Answers

Yes, the modifier keyword order is flexible. It does the same thing on the left or the right of the type. The same thing goes for const.

I prefer the modifier after the type, because it allows you to read from right to left to get the plain-English definition.

int volatile * foo; // "foo is a pointer to a volatile int"
int * volatile foo;  // "foo is a volatile pointer to an int"
int const * foo; // "foo is a pointer to a constant int"
int * const foo; // "foo is a constant pointer to an int"

So I self-standardize on

int volatile foo;
like image 51
MikeJfromVA Avatar answered Nov 02 '22 11:11

MikeJfromVA