Should ALL global variables be volatile-qualified?

后端 未结 5 1197
走了就别回头了
走了就别回头了 2020-12-31 09:48

In this example, does correctness require global_value to be declared volatile?

int global_value = 0;

void foo () {
    ++ global_v         


        
5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-31 10:24

    No, the volatile keyword is not necessary here. Since global_value is visible outside the function bar, the compiler must not assume that it remains the same if another function is called.

    [Update 2011-07-28] I found a nice citation that proves it all. It's in ISO C99, 5.1.2.3p2, which I am too lazy to copy here in its entirety. It says:

    At certain specified points in the execution sequence called sequence points, all side effects of previous evaluations shall be complete and no side effects of subsequent evaluations shall have taken place.

    Sequence points include:

    • The call to a function, after the arguments have been evaluated (6.5.2.2).
    • The end of a full expression: [...] the expression in an expression statement (6.8.3); [...]

    There you have your proof.

提交回复
热议问题