Confused

Hi programmers when we write i++ it means i = i+1 right
but watch here
1
2
3
4
5
6
7
8
9
int  main()
{
	int   z  =  45;
	int  x  =  0;
	x = z++;
	cout<<x<<'\t'<<z<<endl;
	system("pause");
}

int the cout statement x shows 45 and z 46 why?
but when i write x = z = z +1;
both x and y shows 46 i don't understand
Both i++ and ++i will increase i by one. The difference is that i++ will return the value of i before i was increased while ++i will return the value of i after i has been increased.

So in your code x will get the value 45, but if you change line 5 to x = ++z; you will see that both x and z will have the same value.
I saw it explained this way in a book which may help.

z++ means "use the value of z first and then change it"

1
2
x = z;
z = z + 1;


++z means "change the value of z first and then use it"

1
2
z = z + 1;
x = z;




Last edited on
if you say
1
2
x=12;
y=x++;

what does this actually mean? It means "assign the value of x to y and immediately after assigning 12 to y, x gets incremented by 1", therefore y==12 and x changes immediately to 13. But what if you say
1
2
x=12;
y=++x;

It means, "first of all, increment x by 1, which makes x=13, then assign x's new value to y." So it makes them both 13.
Yup
Topic archived. No new replies allowed.