What is the C/C++ volatile modifier for?

Asked

Viewed 7,627 times

13

I’ve seen in some codes on C/C++ statements like this:

volatile int i = 0;

I would like to know what the modifier is for volatile and in which cases should I use it.

2 answers

12


A variable volatile indicates to the compiler that the variable can be modified without the knowledge of the main program. Thus, the compiler cannot safely predict whether it can optimize program snippets where this variable is.

For example:

int x = 100;

while(x == 100)
{
// codigo
}

In this case, the compiler will verify that it can perform this optimization, because the value of x is never changed:

while(true)
{
// codigo
}

What can be seen in assembly generated:

$LL2@main:   
    jmp SHORT $LL2@main

While using volatile, this optimization is not done.

volatile int x = 100;

while(x == 100)
{
// codigo
}

As can be seen in assembly generated:

$LL2@main:
    cmp DWORD PTR _x$[ebp], 100
    je  SHORT $LL2@main

7

A variable or declared object volatile prevents the compiler from performing code optimization involving volatile objects, thus ensuring that each volatile variable assignment reads the corresponding memory access.

Without the keyword volatile, compiler knows if such variable does not need to be reread from memory at each use, as there should be no recordings to its memory location of any other process or segment.

According to the C++11 ISO Standard the keyword volatile serves only for use for access to hardware, not use it for communication inter-thread. For communication inter-thread, to biblioteca padrão prove the std::atomic<T>.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.