Hi there, I hope you all are fine
let us talk a little bit about C++ programming language and take a deep dive into assignment operator (=) and post-increment operator (++)
#include <iostream>
using namespace std;
int main()
{
int x = 5;
x = x++;
cout<<x; // 5
return 0;
}
The question is why x equals 5?
First of all, let us divide this statement into 3 parts
1) x
2) =
3) x++;
As the assignment operator = assigns the right side to the left side and returns the left side we should start with the right-most part which is x++;
x++ This is a post-increment operator which means it will evaluate the current value (5), and increment the value in memory for the upcoming operations (6).
When you use x++, the value of x is first used in the expression where x++ appears, and then x is incremented by 1.
until now everything is clear?
again
so x++; will do two things,
it'll give you a temporary value (we can say) which is 5, and,
change x's real value in memory by 1.but, if we say x = 900; we obviously say in this statement:
change x's real value in memory and assign 900 to it.
If you notice same bold phrase repeated which means the same behavior in 2 different situations normal assignment and post-increment.
so finally the x = part will overwrite (x = 6 in memory) so it will remain 5.
I hope you got it 👍
Top comments (1)
You can use pythontutor for more visualization of memory, Actually, it's a very great tool.