volatile - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

volatile

ratnam_eeeratnam_eee Posts: 5Member
hi can any body explain what it is volatile identifier applications of it how ot use
can variable be both constant and volatile
reply me

where i can get information regarding volatile

Comments

  • LundinLundin Posts: 3,711Member
    : hi can any body explain what it is volatile identifier applications of it how ot use
    : can variable be both constant and volatile
    : reply me
    :
    : where i can get information regarding volatile
    :


    volatile means that the variable's value might be changed at any time from an external source. You use it when defining hardware-related variables to prevent the compiler from optimizing them away.
    If you have a code that looks like this:

    int x = 5;

    ... /* lots of code not affecting x */

    if(x==5)
    {
    doSomething();
    }

    The compiler knows that no code has changed the value of x, so when it is about to generate the executable it can skip the if-statement since it is always true, and therefore doSomething() will always be executed.

    But if x was a hardware register of some sort, it's value could be changed by hardware during the executiong of "lots of code not affecting x". Then the if-statement wouldn't always be true anymore, and the program wouldn't work since the compiler optimized away that statement.

    By declaring x as

    volatile int x;

    you tell the compiler to not optimize any code using the variable x.
    volatile can be combined with const, in case the harware is read-only.
Sign In or Register to comment.