Where all to use volatile keyword in C

前端 未结 5 1631
余生分开走
余生分开走 2021-01-20 04:37

I know volatile keyword prevents compiler from optimizing a variable and read it from memory whenever it is read. Apart from memory mapped registers, what are all the situat

5条回答
  •  执笔经年
    2021-01-20 05:14

    In C microcontroller applications using interrupts, the volatile keyword is essential in making sure that a value set in an interrupt is saved properly in the interrupt and later has the correct value in the main processing loop. Failure to use volatile is perhaps the single biggest reason that timer-based interrupts or ADC (analog-digital conversion) based interrupts for example will have a corrupted value when flow of control resumes after the processor state is returned post-interrupt. A canonical template from Atmel and GCC:

    volatile uint8_t flag = 0;
    
    ISR(TIMER_whatever_interrupt)
    {
        flag = 1;
    }
    
    while(1) // main loop
    {
        if (flag == 1)
        {
            
            flag = 0;
        }
    }
    

    Without the volatile it's guaranteed to not work as expected.

提交回复
热议问题