简体   繁体   中英

C++ Boolean with Integers

OK so obviously this question might sound dumb for more experienced people, but, for the following lines the result I get is 0 :

int x = 2,
y = -2;

cout << (x++ - y && (--x + y));

I understand it means that either one of these two expressions equals 0, but how? As far as I understand, this should be (3 && -1)?

Also, a little subquestion: when does x++ exactly take effect? On the next occurance of x within the same expression, after the left-shift operator within the same line, or in the next statement?

Thank you!

As far as I understand, this should be (3 && -1)?

you understand wrong:

first left side is fully evaluated, as it is necessary for short circuit evaluation with logical and (details can be found here )

x++ - y == 4 // as result of x++ == 2 so (2-(-2)), after that x == 3

result is true so right side is evaluated:

--x + y ==  0 // as result of --x == 2 so (2+(-2)), after that x == 2

result on the right is false so result of and is false as well which printed by std::ostream as 0

Note: short circuit evaluation of logical or and and operations make such code valid (making them sequenced) but you better avoid such questionable expressions. For example simple replacing logical and to binary would make it UB.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM