Different behavior in different scenarios "warning C4800:" int ": forced bool value" true "or" false "

I cannot understand the following behavior of this warning.

case 1:
bool read = (33 & 3) ; //No Warning issued by vs 2013

case 2:
int b = 33;
bool read = (b & 3) ; //Now compiler is generating C4800 warning.  

Why does the compiler generate a warning in case 2, until it issues a warning in case 1.

+4
source share
3 answers

In the first case, you create a boolean variable from an expression. maybe

std::cout << std::is_constructible<decltype((33 & 3)), bool>::value<<std::endl; // output: 1

In the second case, you build the int variable from the expression. Type of this expressionint

std::cout << typeid(b & 3).name() << std::endl; // output: i

And finally, you use implicit type conversion from int to bool and get a warning.

+1
source

C4800 - - bool .
.

( ) - , (bool V++) booleans.

, .

, :

bool read = (b & 3) != 0;
+3

, , , (, , ). , , ? .

However, in practice, I would ignore or even turn off this warning. Consider a test case for a bit: bool negative = byte & 0x80;. This code is what I would call an idiomatic code, and it generates a warning. For me, this is proof of why this warning is bad.

+1
source

Source: https://habr.com/ru/post/1613295/


All Articles