Why is volatile needed in C?

前端 未结 18 2450
攒了一身酷
攒了一身酷 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:27

    As rightly suggested by many here, the volatile keyword's popular use is to skip the optimisation of the volatile variable.

    The best advantage that comes to mind, and worth mentioning after reading about volatile is -- to prevent rolling back of the variable in case of a longjmp. A non-local jump.

    What does this mean?

    It simply means that the last value will be retained after you do stack unwinding, to return to some previous stack frame; typically in case of some erroneous scenario.

    Since it'd be out of scope of this question, I am not going into details of setjmp/longjmp here, but it's worth reading about it; and how the volatility feature can be used to retain the last value.

提交回复
热议问题