Where all to use volatile keyword in C

前端 未结 5 1669
余生分开走
余生分开走 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:09

    Apart from memory mapped registers, what are all the situations where we need to use volatile?

    If

    1. execution is purely sequential (no threads and no signals delivered asynchronously);
    2. you don't use longjmp;
    3. you don't need to be able to debug a program compiled with optimizations;
    4. you don't use constructs with vaguely specified semantics like floating point operations;
    5. you don't do useless computations (computations where the result is ignored) as in a benchmark loop;
    6. you don't do timings of any pure computations, that is anything that isn't I/O based (I/O based such as timings of accesses of network requests, external database accesses)

    then you probably have no need for volatile.

提交回复
热议问题