This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Declare variables as volatile

Is it right to declare all  variables as volatile so that if optimization run, it won't ignore it.

Like global, function arguments etc.

  • No, it is not correct.

    You should only apply the volatile qualifier where there is a specific need for it.

     

  • Aamir Ali said:
    Is it right to declare all  variables as volatile so that if optimization run, it won't ignore it.

    No. The volatie qualifier tells the compiler about possible side-effects of accessing a variable. So the compiler won't optimize it.
    However, in some cases the compile rknows that there cannot be any side-effects and ignores the volatile keyword (this is true for almost all local variables, as the compiler does exactly know whether any reference to it is given away or not).

    There are usually only two reasons for declaring a variable volatile. First, when readign it or writing to it does mroe than jsut change its value (this is true for many hardware registers) of if they are accessed outside the program flow, either by DMA or by an ISR.

    All othe rvariables shouildn't be volatile or less efficient code will be generated without need.

**Attention** This is a public forum