1

When compiling on Windows, the compiler gives this warning:

forcing value to bool 'true' or 'false' (performance warning)

It arises when I do something like:

int a = ...
bool b = (a & (1 << 3);

The solution is either to do:

bool b = (a & (1 << 3)) != 0;

or to use an int instead of a bool.

The question is: why the first case incurs a performance issue but not the second? Also, why isn't there the warning when I do:

if (a & (1 << 3)) {
  ...
}

Because in this case, the value is converted to bool isn't it?

0xh3xa
  • 4,801
  • 2
  • 14
  • 28
Jojolatino
  • 696
  • 5
  • 11
  • 1
    Could you add the compiler information? As well as the compilation flags? – cigien Apr 29 '20 at 20:51
  • The `if` only tests for *truthful* values, it doesn't necessarily cast to `bool`. – tadman Apr 29 '20 at 20:52
  • Does this answer your question? [warning C4800: 'BOOL' : forcing value to bool 'true' or 'false' (performance warning)](https://stackoverflow.com/questions/22498767/warning-c4800-bool-forcing-value-to-bool-true-or-false-performance-war) – cigien Apr 29 '20 at 20:52
  • @tadman — the code does not **cast** anything. You can see that by looking at it. The result of the expression is “contextually converted to bool”, which may or may not involve generating an actual bool value, since the calculation itself might set the appropriate processor flags. – Pete Becker Apr 29 '20 at 21:37
  • @PeteBecker That's what I was trying to say, though you do have a more specific approach there. – tadman Apr 29 '20 at 21:54

1 Answers1

3

This warning is of the obsolete Visual Studio 2015 compiler spelled with incorrect words in some context. Now it sounds more correct

Implicit conversion from int to bool. Possible information loss

Compiler Warning (level 4) C4800

273K
  • 29,503
  • 10
  • 41
  • 64