What is the C / C ++ volatile operator?

6

I've seen some code in C / C ++ statements like this:

volatile int i = 0;

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

    
asked by anonymous 22.03.2014 / 15:16

2 answers

6

A variable volatile tells the compiler that the variable can be modified without the knowledge of the main program. This way, the compiler can not safely predict whether it can optimize program streams where this variable is located.

For example:

int x = 100;

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

In this case, the compiler will check that it can do 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
}

How can be seen in% generated%:

$LL2@main:
    cmp DWORD PTR _x$[ebp], 100
    je  SHORT $LL2@main
    
22.03.2014 / 15:23
4

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

Without the volatile keyword, the compiler knows if such a variable does not need to be reread from memory in each usage, as there should not be any writes to its memory location from any other process or thread.

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

    
22.03.2014 / 18:15