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 Avelino 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:

[email protected]:   
    jmp SHORT [email protected]

While using volatile , this optimization is not done.

volatile int x = 100;

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

How can be seen in% generated%:

[email protected]:
    cmp DWORD PTR _x$[ebp], 100
    je  SHORT [email protected]
    
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