Why not always use compiler optimization?

前端 未结 9 1564
野性不改
野性不改 2020-12-08 02:17

One of the questions that I asked some time ago had undefined behavior, so compiler optimization was actually causing the program to break.

But if there is no undefi

9条回答
  •  青春惊慌失措
    2020-12-08 02:57

    One example is short-circuit boolean evaluation. Something like:

    if (someFunc() && otherFunc()) {
      ...
    }
    

    A 'smart' compiler might realize that someFunc will always return false for some reason, making the entire statement evaluate to false, and decide to not call otherFunc to save CPU time. But if otherFunc contains some code that directly affects program execution (maybe it resets a global flag or something), it now won't perform that step and you program enters an unknown state.

提交回复
热议问题