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.