Volatile variable

前端 未结 6 1525
梦谈多话
梦谈多话 2020-12-25 15:12

Where is a volatile variable stored in the program memory(in which section) ?

6条回答
  •  天命终不由人
    2020-12-25 15:55

    volatile has nothing to deal with storage class.

    volatile just tells the compiler or force the compiler to "not to do the optimization" for that variable. so compiler would not optimize the code for that variable and reading the value from the specified location, not through interal register which holds the previous value.

    So, by declaring variable as volatile.. it gives garrantee that you will get the latest value, which may be alterred by an external event.

    your code may be work fine if haven't declare that variable as volatile, but there may be chance of not getting correct value sometimes.. so to avoid that we should declare variable as volatile.

    volatile is generally used when dealing with external events, like interrupts of hardware related pins.

    example. reading adc values.

    const voltile means you can not modify or alter the value of that variable in code. only external event can change the value.

    controller pins are generally defines as volatile. may be by declaring variable as volatile controller will do "read by pin" not "read by latch"... this is my assumtion. may be wrong...

    but still there is lots of confusion when to choose variable as volatile..

    A variable should be declared volatile whenever its value could change unexpectedly. In practice, only three types of variables could change:

    1. Memory-mapped peripheral registers

    2. Global variables modified by an interrupt service routine

    3. Global variables within a multi-threaded application

    Link : http://eetimes.com/discussion/beginner-s-corner/4023801/Introduction-to-the-Volatile-Keyword

    So It is proffered to variable as volatile in such cases.

提交回复
热议问题