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;"
>Solution :
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.
Since Delay == false, the return value of the ternary operator is -1. The fact that you’re operating on a boolean 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