Pre vs. Post-Increment

I have a question related to Pre vs. Post-Increment Operations in Programming.
Having read the C++ for Programmers Article related to Operators,
I learned that Pre and Post-Increment operators behave differently in nature.

The code snippet below does not follow the concepts discussed in the Pre vs. Post-Increment section in the Operators Article (C++ for Programmers):
Operators Article (C++ for Programmers)

Code Snippets:

#include <iostream> int main() { // This code returns 4 as answer, where it should be 3 (according to the article) int x= 1; x = x++ + ++x ; std::cout<< x << std::endl; return 0; }
#include <iostream> int main() { //This code returns 5 as answer, where it should be 3 (according to the article) int x= 1; x = ++x + x++; std::cout<< x << std::endl; return 0; }

Please explain why do I get these outputs, and if there’s any misunderstanding from me with learning the concepts, then also let me know.
Thanks.

If you double check the examples they’re using different variables in the examples. As written this is something you’d never do so it’s not too much to worry about.

Edit: Of course I find it ten seconds later, see the examples of undefined behaviour matching yours at- https://en.cppreference.com/w/c/language/eval_order

1 Like

Well if you consider the results to be “undefined” then, why does it give me fixed values of 4 and 5 respectively?

You’ll want to have a wee look into what ‘undefined behaviour’ actually means, that page even hyperlinks the definition. If it’s not clear then there’s plenty of guidance online to be found with a quick search e.g. c++ - Undefined, unspecified and implementation-defined behavior - Stack Overflow

1 Like

Thanks, I got it now! Really appreciate it.

1 Like