2

Is there any performance difference in situations when bool is initialized with a value different from 0 and 1?

I have read in Optimizing C++ by Agner Fog that:

Boolean variables are overdetermined in the sense that all operators that have Boolean variables as input check if the inputs have any other value than 0 or 1, but operators that have Booleans as output can produce no other value than 0 or 1. This makes operations with Boolean variables as input less efficient than necessary.

Can anybody explain what does it mean?

plasmacel
  • 8,183
  • 7
  • 53
  • 101
Splend
  • 21
  • 1
  • 1
    The book you've linked gives detailed examples and explains further just below that quote. If your question is "Should I never use bool again?", then the answer would be "No"! – DeiDei Apr 19 '17 at 15:46
  • 2
    *"all operators that have Boolean variables as input check if the inputs have any other value than 0 or 1"* That is not correct. The other text *"Boolean variables are stored as 8-bit integers with the value 0 for false and 1 for true."* is also not quite correct, the bits that make up `true` and `false` are not specified by the standard and compiler specific. You should consider ignoring everything in that PDF and read something from [here](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – nwp Apr 19 '17 at 15:47
  • @nwp I thought `false` was specified as `0` and all other numbers are `true`. – NathanOliver Apr 19 '17 at 15:53
  • @NathanOliver That only applies to integers, not to `bool`s. Possibly also applies to pointers, except that `nullptr` isn't necessarily all bits being `0`. – nwp Apr 19 '17 at 15:55
  • @nwp Note that AF's book is not about C++ in general, it is about specific implementations on specific platforms, as advertised at the beginning. Did you check what g++/clang++/sunCC (I only tested those 3) generate for `bool a,b,c;void fun(){c=a&&b;}` on x86_64-linux? Maybe that's a common bug in those compilers, but bugs can be relevant information. On the other hand, I agree that the statements in the book are too strong and the bool situation should not be presented as being so absolutely, unfixably broken. – Marc Glisse Apr 19 '17 at 16:07
  • @MarcGlisse No I missed that. It is undefined behavior which is even worse. Would recommend deleting immediately. – nwp Apr 19 '17 at 16:14

0 Answers0