Why is volatile needed in C?

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

    Another use for volatile is signal handlers. If you have code like this:

    int quit = 0;
    while (!quit)
    {
        /* very small loop which is completely visible to the compiler */
    }
    

    The compiler is allowed to notice the loop body does not touch the quit variable and convert the loop to a while (true) loop. Even if the quit variable is set on the signal handler for SIGINT and SIGTERM; the compiler has no way to know that.

    However, if the quit variable is declared volatile, the compiler is forced to load it every time, because it can be modified elsewhere. This is exactly what you want in this situation.

提交回复
热议问题