--x x-- ??????? help?

Hey guys, still anewbie here, someone was really helpful before! can someone please explain this to me?

Just wondering if you know this?

What is the difference between say --x and x-- in C++ code?
If you do --x, x is decremented before any operation is done do it. If you do x--, it will be decremented after the operation.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

int main()
{
	int x = 2;

	cout << --x << endl;
	cout << x-- << endl;
	cout << x << endl;

	return 0;
}


As you can see with this program, the first cout will display 1, since x is decremented right away. The second will also display 1, since it first displays x's value, then decrement it. If we output x once more, we see that its value is now 0.
thankyou so much man !!!!
It is a bit misleading to say it decrements after it returns. It actually decrements first but stores the original value and then returns that original value. The return must always happen last. x++ will often be optimized to ++x when the return value is not being used.
Last edited on
Topic archived. No new replies allowed.