Trying to do the following:

int A = 1; bool B = (bool)A; 

I get a warning when compiling: warning C4800: 'int': forcing value to bool 'true' or 'false' (performance warning). Why? How to deal with it!?

  • Tell us why you need to turn an int into a bool . Usually this is just not necessary. - VladD
  • 2
    Use A != 0 , see stackoverflow.com/questions/206564/… - Costantino Rupert
  • @ Kitty: my crystal ball says that the topstarter would use BOOL instead of bool in that case. - VladD
  • And what does the compiler say when using static_cast? - skegg
  • @VladD cyl in C ++ is a bool data type, I think it makes sense to use it and not int - rejie

2 answers 2

Did not drive. The fact is that now all compilers are optimizing. In this context, it turns out that the variable A is not needed at all. And the compiler can easily simply reduce everything to bool B = true; . At least if the code is exactly like that. If not, then please give a more advanced example.

The warning C4800 will respond best to MSDN .

This warning is generated when this is a bool. This is the case where the variable has been defined as the type bool. If you cant be bool, then you can add "! = 0" to the expression, which gives the expression type bool. Casting the expression for the bool will not be a warning, which is by design.

In short, in a simple way, Microsoft says: "Do not use a cast to a boolean type." Probably the problem is that the compiler still needs to do an extra step. Namely insert test !=0 .

  • one
    I think it’s not about saving the compiler’s actions, but about installing (in the heads of the developers) how to write programs. - avp
  • @gecube My function uses strcpy_s, etc. if the calculations were successful, then return true. Then one more question - if my function does not return an error code, but is limited by the answer whether or not the correct use of bool for the return value will be correct and sufficient !? - rejie
  • @rejie, I think so, right. - gecube
  • @rejie, have you ever wondered why ( for what purpose ) the original strcpy() returns the address of the receiver? - avp
  • @avp address of the receiver or NULL in case of an error, honestly did not think, for what? And why does strcpy_s do otherwise? - rejie 2:29

What do you wonder about this warning? He absolutely hints at you on an implicit type conversion. Want to do that? No problem: use static_cast for example or a C-style cast (less preferred)