Question Details

No question body available.

Tags

if-statement type-conversion integer boolean expression

Answers (2)

April 13, 2026 Score: 0 Rep: 1 Quality: Low Completeness: 70%

C++, as is C, define implicit casts. There's implicit contextual conversions to bool for expression in if conditions, && perands, etc. which will cast an integer to true (non-zero) or false (zero). And there's integer promotions which will, as a general rule of thumb, promote a type to another if there's no loss of information from that promotion. So for an equality comparison like a == true, casting a to a bool would "reduce" our information about a (32-bits vs. 1-bit), while casting true to an integer (1) preserves the information we know about true to fully construct it back from its integer representation.

April 13, 2026 Score: 0 Rep: 1,015 Quality: Low Completeness: 50%

When comparing a valriable to the values true or false, the variable is cast to a boolean value. A boolean variable is generally treated as a single bit (1 for true, and 0 for false). Taking any number you can check which result is likely by whether it is odd (lowest bit equal to 1) or even (lowest bit equal to 0). The compiler does this by masking any 32 or 64 bit value with literal '1' to create a simple boolean.

However, in the expression if (a) there is no cast so the implied expression is if (a is non-zero).