What kinds of optimizations does 'volatile' prevent in C++?

后端 未结 8 1881
Happy的楠姐
Happy的楠姐 2020-11-27 17:04

I was looking up the keyword volatile and what it\'s for, and the answer I got was pretty much:

It\'s used to prevent the compiler from o

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 17:28

    usually compiler assumes that a program is single threaded, therefore it has complete knowledge of what's happening with variable values. a smart compiler can then prove that the program can be transformed into another program with equivalent semantics but better performance. for example

    x = y+y+y+y+y;
    

    can be transformed to

    x = y*5;
    

    however, if a variable can be changed outside the thread, compiler doesn't have a complete knowledge of what's going on by simply examining this piece of code. it can no longer make optimizations like above. (edit: it probably can in this case; we need more sophisticated examples)

    by default, for performance optimization, single thread access is assumed. this assumption is usually true. unless programmer explicitly instruct otherwise with the volatile keyword.

提交回复
热议问题