Why is volatile needed in C?

前端 未结 18 2499
攒了一身酷
攒了一身酷 2020-11-22 04:07

Why is volatile needed in C? What is it used for? What will it do?

18条回答
  •  借酒劲吻你
    2020-11-22 04:28

    My simple explanation is:

    In some scenarios, based on the logic or code, the compiler will do optimisation of variables which it thinks do not change. The volatile keyword prevents a variable being optimised.

    For example:

    bool usb_interface_flag = 0;
    while(usb_interface_flag == 0)
    {
        // execute logic for the scenario where the USB isn't connected 
    }
    

    From the above code, the compiler may think usb_interface_flag is defined as 0, and that in the while loop it will be zero forever. After optimisation, the compiler will treat it as while(true) all the time, resulting in an infinite loop.

    To avoid these kinds of scenarios, we declare the flag as volatile, we are telling to compiler that this value may be changed by an external interface or other module of program, i.e., please don't optimise it. That's the use case for volatile.

提交回复
热议问题