I have the following code where behavior is not clear to me. Can some one please help how conditional operator evaluate the following code and output ans as 1
#include
int main() {
bool delayMessages=0;
bool Delay = false;
delayMessages += Delay ? 1 : -1;
std::cout << "Hello world!"<<delayMessages;
return 0;
}
Ans: Hello world!1
Can soemone please help how thsi code is evaluated "delayMessages += Delay ? 1 : -1;"
The expression on the right hand side is evaluated like an if-statement.
if (Delay == true)
return 1;
else
return -1;
The result is then used for the +=
assignment.
In the C++20 draft standard that's
7.6.19 (6) (Assignment and compound assignment operators)
The behavior of an expression of the form
E1 op= E2
is equivalent toE1 = E1 op E2
except that E1 is evaluated only once. [...]
Since Delay == false
, the return value of the ternary operator is -1
. The fact that you're operating on a bool
ean instead of an int
can make it look like you got the +1
back.
Note that you get a compiler warning C4804:
warning C4804: '+=': unsafe use of type 'bool' in operation
Is it undefined behavior? No.
7.6.19 (6) (Assignment and compound assignment operators)
[...] For += 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
7.3.8 (2) (Integral conversions)
If the destination type is bool, see 7.3.14.
which says
7.3.14 (1) (Boolean conversions)
A prvalue of arithmetic, unscoped enumeration, pointer, or pointer-to-member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true.
So the -1 is converted to true
and true
prints as 1.