Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

what is the output of conditional operator with unary operator

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;"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading