C
C#2d ago
Sebby

✅ What's the difference between ++variable and variable++?

I understand the complier sees the compound variable operators differently depending if it's before or after the variable, but I'm not sure how. Can someone explain this to me like I'm five?
14 Replies
jcotton42
jcotton422d ago
int x = 1;
int y = x++;
// y is 1, x is 2
int z = ++x;
// z is 3, x is 3
int x = 1;
int y = x++;
// y is 1, x is 2
int z = ++x;
// z is 3, x is 3
Sebby
SebbyOP2d ago
So with x++, y stays the same as x's original value, while x goes up by one? What about z?
ACiDCA7
ACiDCA72d ago
no x gets assigned to y first then gets incremented while in z case x gets incremented first and then gets assigned to z
jcotton42
jcotton422d ago
I will say, if understanding your code relies on understanding this distinction, you probably should change it.
Sebby
SebbyOP2d ago
I'm learning the basics on mslearn I don't entirely understand, but thanks for the info
ACiDCA7
ACiDCA72d ago
lets break it doen more
int x = 1;
int y = x++;
//is the same as
//y=x
//x=x+1
int z = ++x;
// is the same as
//x=x+1
//z=x
int x = 1;
int y = x++;
//is the same as
//y=x
//x=x+1
int z = ++x;
// is the same as
//x=x+1
//z=x
Sebby
SebbyOP2d ago
That helped a lot. I get the first part now Like jcotton put above, the 2 is taken from the first part when x is redefined as 2 and then z becomes the same as your end comments? Is that why z becomes the same?
Angius
Angius2d ago
++x — increment, then use x++ — use, then increment
Sebby
SebbyOP2d ago
Thanks for the help everyone!
▬▬ι═══════ﺤ
x=1; y=0; y = x++ means : y = x; x = x+1; -------- y = ++x means : x=x+1; y=x;
Mąż Zuzanny Harmider Szczęście
basically: i++ means after iteration add 1 while ++i means before iteration add 1
Jimmacle
Jimmacle20h ago
what do you mean by iteration? if you're talking about using it in a loop, that's not true prefix or postfix only affects the value returned by the expression, if you aren't using the return value (which the 3rd statement of a for loop doesn't, and neither does a standalone increment) they're equivalent
SleepWellPupper
SleepWellPupper17h ago
This seems to be solved, perhaps $close it.
MODiX
MODiX17h ago
If you have no further questions, please use /close to mark the forum thread as answered

Did you find this page helpful?