Loading…

The meaning of volatile in C

 

What does the keyword volatile mean and when it can be applied? In case you know the formal meaning, try to provide a situation example when volatile will actually be useful.

 

The term volatile tells the compiler that the variable value can be changed externally. This can be powered by an operating system, hardware, or other thread. Since the value may change, the compiler loads it from memory each time.

 

Volatile integer variable can be declared in the following way:

 

int volatile x;

volatile int x;

 

If you want to declare a pointer to this variable, you need to run the following commands:

 

volatile int * x;

int volatile * x;

 

A volatile pointer to non-volatile data is pretty rarely used in practice. Still, let’s discuss this case as well:

 

int * volatile x;

 

In case you want to declare a volatile pointer to a volatile memory area, you need to do the following actions:

 

int volatile * volatile x;

 

Volatile variables are not optimized and this fact can be useful. Take a look at the following function:

 

int opt ​​= 1;

void Fn (void) {

    start:

        if (opt == 1)

            goto start;

        else

            break;

}

At first glance, the program seems to be cycled. The compiler can optimize it in the following way:

 

void Fn (void) {

    start:

    int opt ​​= 1;

    if (true)

        goto start;

}

 

This way, the cycle will definitely become infinite. However, an external operation gives you an opportunity to write 0 to the opt variable and break the cycle.

 

Actually, you can prevent this optimization with the help of the keyword volatile. For example, you can declare that some system external element changes a variable:

 

volatile int opt ​​= 1;

void Fn (void) {

    start:

    if (opt == 1)

        goto start;

    else

        break;

}

Volatile variables are used as global variables in multi-threaded applications — any flow can change common variables. This way, we do not want to optimize these variables.

 


Leave a Comment