Forum Discussion

Altera_Forum's avatar
Altera_Forum
Icon for Honored Contributor rankHonored Contributor
20 years ago

why use the "volatile" keyword

Hey guys, I'm working on some ISR sofware development, and I am wondering why the software developer's hand book declares variables as "volatile int*" and "volatile int" rather then just "int*" and "int". The manual says that "the volatile keyword only prevents the compiler from optomizing out accesses using the pointer". Does this mean if the volatile keyword isn't used the compiler will ignore statements involving referencing and dereferencing pointers? Thanks for the help!

-Jon

2 Replies

  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    It's a bit hard to say why without referring to a specific example, however volatile is a standard C keyword and you should probaby refer to "The C Programming Language" by Kernighan and Ritchie.

    However volatile is used when you want to force the compile to actually load a variable from memory.

    For example if I have some code

    int a = *0x80000; //Load a from memory

    /*

    Do stuff

    */

    b = *0x80000;

    I the Do stuff code did not change the memory location 0x80000 the compiler may try to optimise and say well I knew what the contents were when I read a so I'll use the value I read before.

    This tends to be a problem when you are reading from something that can change such as;

    a piece of hardware

    or a piece of memory written to by some hardware or another piece of software (eg. foreground code and an ISR)