When programming in Visual C ++, I think that every developer is used to view a warning
warning C4800: 'BOOL' : forcing value to bool 'true' or 'false'
occasionally. The reason, obviously, is that BOOL is defined as int and directly assigning any of the built-in numeric types to bool is considered a bad idea.
So, now my question is asked by any built-in numerical type (int, short, ...) that should be interpreted as a boolean, what is your preferred way to actually store this value in a variable of type bool ?
Note: when mixing BOOL and bool, it is probably a bad idea, I think the problem will inevitably appear on Windows or somewhere else, so I think this question is neither Visual C ++ nor Windows. Sub>
Given int nBoolean; I prefer this style:
bool b = nBoolean?true:false;
The alternatives are listed below:
Is there any preferred way? Justification?
I have to add: since I only work with Visual-C ++, I can’t say whether this is a question related to VC ++, or if there is a problem with other compilers. Therefore, it would be interesting to learn from g ++ or users how they handle the int-> bool case.
Regarding the C ++ standard: as David Thornley notes in a comment, the C ++ standard does not require this behavior. In fact, this explicitly allows this, so it can be considered a weirdness of VC ++. To quote the N3029 project (this is what I have around atm.):
4.12 Logical transformations [conv.bool]
The value of arithmetic, a non-taxable enumeration, a pointer or a pointer to a member type can be converted to a prvalue of type bool. A null value, a null pointer value, or a null term pointer value is converted to false; any other value is converted to true. (...)