Volatile in C++11

Whether it is optimized out depends entirely on compilers and what they choose to optimize away. The C++98/03 memory model does not recognize the possibility that x could change between the setting of it and the retrieval of the value. The C++11 memory model does recognize that x could be changed. However, it doesn’t care. … Read more

Should std::atomic be volatile?

Is the compiler free to cache the value of the atomic variable and unroll the loop? The compiler cannot cache the value of an atomic variable. However, since you are using std::memory_order_relaxed, that means the compiler is free to reorder loads and stores from/to this atomic variable with regards to other loads and stores. Also … Read more

When would I use const volatile, register volatile, static volatile in C++?

register volatile int T=10; volatile qualifier means that the compiler cannot apply optimizations or reorder access to T, While register is a hint to the compiler that T will be heavily used. If address of T is taken, the hint is simply ignored by the compiler. Note that register is deprecated but still used. Practical … Read more

C: Volatile Arrays in C

Yes, volatile is required, and the right declaration is: volatile unsigned char *my_data; This declares my_data to be a pointer to volatile unsigned char. To make the pointer itself volatile, you’d need this instead: unsigned char *volatile my_data; And of course, both the pointer and the pointed-to data may be volatile: volatile unsigned char *volatile … Read more

Is the order of writes to separate members of a volatile struct guaranteed to be preserved?

c They will not be reordered. C17 6.5.2.3(3) says: A postfix expression followed by the . operator and an identifier designates a member of a structure or union object. The value is that of the named member, 97) and is an lvalue if the first expression is an lvalue. If the first expression has qualified … Read more