I don't understand why this function is equal to 1

Pages: 12
CodeMode wrote:
It was a very good example and I fully understood what you meant by that but is it the same case for suffix as well ? I mean what if it's x++ ? then the result will be completely different right ? take this new one as an example:
 
std::cout << (x++ == 7 && x + 2 >= 10);

My point is that it's always possible to write the code in a way that avoids having to modify a variable in the middle of an expression, but exactly how that code should look like depends very much on the situation. There is no simple formula to follow that works everywhere.

Your example could be rewritten as
1
2
++x;
std::cout << (x - 1 == 7 && x + 2 >= 10);
or
1
2
++x;
std::cout << (x == 8 && x >= 8);
or
1
2
++x;
std::cout << (x == 8);


It's also possible to do the increment afterwards as
1
2
std::cout << (x == 7 && x + 3 >= 10);
++x;
or
1
2
std::cout << (x == 7 && x >= 7);
++x;
or
1
2
std::cout << (x == 7);
++x;
Last edited on
You're right.
Thanks Peter.
Last edited on
this stuff really should not show up in production code. Its a 'confuse the student' test question, or interview question, but out in the wild writing real code, you want to make such statements as simple and easy to follow as possible. There isnt any efficiency consideration most of the time -- you are gonna increment it, before or after something, so do it that way explicitly rather than make someone else or even yourself figure it out when reading it someday. Bitwise logic and weird boolean stuff should be done as readable as possible unless you can prove it has a meaningful performance impact to do it another way (in which case comment it on what it is doing and that it was faster this way).
Topic archived. No new replies allowed.
Pages: 12