Search code examples
c++typesoperationboolean-operations

What operations can you perform with bool and int operators in C++?


I have a variable, which value can differ from 0 to 1, so I would like to use a bool type for holding this value.

In C++ based on this idea what operations can I do, the type of the first operand being bool and the second's being int or float?

For example, is this valid?

bool exists;
int value;
(...)
value += exists;
value *= exists;

If yes, until c++ converts these values into their binary appropriates and finds no problems doing the operations on those binary numbers, it is valid to do the operations with operands that differ?


Solution

  • Yes these operations exist, they are found in the C++ standard section 13.6 (note, bool is an integral type which makes it an arithmetic type as well):

    For every triple (L, VQ, R), where L is an arithmetic type, VQ is either volatile or empty, and R is a promoted arithmetic type, there exist candidate operator functions of the form

    VQ L & operator=(VQ L &, R );
    VQ L & operator*=(VQ L &, R );
    VQ L & operator/=(VQ L &, R );
    VQ L & operator+=(VQ L &, R );
    VQ L & operator-=(VQ L &, R );
    

    The semantics are defined in section 5.18:

    The behavior of an expression of the form E1 op = E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once. In += and -=, E1 shall either have arithmetic type or be a pointer to a possibly cv-qualified completely-defined object type. In all other cases, E1 shall have arithmetic type.

    and

    If the left operand is not of class type, the expression is implicitly converted (Clause 4) to the cv-unqualified type of the left operand.