C ++ Volatile position of type quantizer in variable definition

I do some research and did not find a good answer, and I hope for a better understanding. I know how to use volatile , but you have a question about what it does when its placement is different in variable declarations, for example.

  • volatile int * ptr;

An integer designated as volatile , and when read / write to this memory location always goes into the memory location.

  • int * volatile ptr;

The pointer value is volatile and when read / write to this memory location always go to the memory location.

This is a subtle difference, but from what I can tell, the difference is in 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, for example, if a volatile quantifier is not a pointer type.

 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 ads do the same for pointers without pointers?

+5
source share
1 answer

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

I prefer the modifier after the type, because it allows you to read from right to left to get a simple 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 standardize myself

 int volatile foo; 
+2
source

All Articles