Fun with uninitialized variables and compiler (GCC)

后端 未结 2 1478
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 11:07

The section §3.9.1/6 from the C++ Standard says,

Values of type bool are either true or false.

Now con

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 11:31

    I'm just curious to know why this sudden change in the behavior of uninitialized bool?

    Disassemble the code and see what the compiler’s doing.

    My guess: since the value is now only used locally, the compiler optimizes it away completely. Since the behaviour is undefined anyway, the compiler can safely just assume any value, e.g. false. This is a pretty obvious optimization since the value of b is constant as far as the compiler is concerned, and the whole logic of the switch is redundant. So why put it in the executable?

    (The important point here is really that b is only ever used locally in the second code, and that in turn will trigger more optimizations even in unoptimized code. The first code has to be inlined before the compiler can do any such optimizations, or the code paths have to be traced which isn’t trivial).

提交回复
热议问题