How can we use volatile variable in C or C++?

Anybody can some good code to understand this.

As far as I know Volatile is used when you don't want the compiler to perform certain optimizations with regards to value changes. (It is as if you say: "The value of this variable may change, even if this doesn't happen in the current program". This may happen in embedded systems for example where this shared memory occurs more.

A simple example would be:

int main(int argc, char* argv[])
{
    int* test = (int*)0x1234;

    while(*test == 2)
    {
    }
}

In this program the value at address 0x1234 will be obtained and checked if it matches 2. If not, the body of the while loop will be executed, but it's empty. When the compiler optimizes (don't know if this goes for all), it doesn't actually check the value at 0x1234 again, but assumes it has not changed. (because there was no code that changes the value there) In case another proces changes the value at 0x1234 that this code will make use of, you can use volatile.

Volatile tells the compiler that a variable may be changed in ways not explicitly specified by the program - According to C: The complete Reference. This means the volatile variable may be changed by forces outside of the current process(usually the kernel, hardware or another process) so don't make any assumption about its current value...

Edited 6 Years Ago by gerard4143: n/a

This article has been dead for over six months. Start a new discussion instead.