What is the performance implication of converting to bool in C++?

前端 未结 11 883
后悔当初
后悔当初 2020-12-03 02:36

[This question is related to but not the same as this one.]

My compiler warns about implicitly converting or casting certain types to bool whereas explicit

11条回答
  •  醉话见心
    2020-12-03 02:52

    In C++ a bool ISA int with only two values 0 = false, 1 = true. The compiler only has to check one bit. To be perfectly clear, true != 0, so any int can override bool, it just cost processing cycles to do so.

    By using a long as in the code sample, you are forcing a lot more bit checks, which will cause a performance hit.

    No this is not premature optimization, it is quite crazy to use code that takes more processing time across the board. This is simply good coding practice.

提交回复
热议问题