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

output and misunderstanding in C++

I want to know why the output is (1), and why In the second assignment to variable b, the expression (i+=2) does not get evaluated. finally how does this program execute step by step?
I am still a beginner.

`

int i = 0;
bool t = true;
bool f = false,
    b;

b = (t && ((i++) == 0));
b = (f && (i += 2 > 0));

cout << i << endl;

`

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 :

Because the && operator short-circuits and f is false, 1 += 2 is not being evaluated.

Since the entire expression can only be true if both operands to && are true, there is no need to evaluate (i += 2 > 0) to determine that the value of the entire expression is false. Given the lack of need to evaluate the second operand in this scenario, many programming languages guarantee that it will not be, including C and C++.

Be careful about using operands with side-effects in boolean expressions.

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