I\'m having a hard time understanding what the difference is between incrementing a variable in C# this way:
myInt++;
and
The pre-fix operator ++myInt is a way of reducing lines: increment the variable before passing it to someplace else. It's also a nice way to reduce readability, since it's uncommon.
MyMethod(++myInt);
vs.
myInt++;
MyMethod(myInt);
To me the second is a lot easier to read.
myInt++ (4 CPU instructions)
LOAD AX, #myInt // From myInt memory to a CPU register
COPY AX, BX
INCREMENT BX
STORE BX, #myInt
// Use AX register for the value
++myInt (3 CPU instructions)
LOAD AX, #myInt // From myInt memory to a CPU register
INCREMENT AX
STORE AX, #myInt
// Use AX register for the value
++myInt will add one to myInt before executing the line in question, myInt++ will do it afterward.
Examples:
int myInt;
myInt = 1;
someFunction(++myInt); // Sends 2 as the parameter
myInt = 1;
someFunction(myInt++); // Sends 1 as the parameter
It is a difference if you are doing
int x = 7;
int x2 = x++;
=> x2 is 7 and x is 8
but when doing
int x = 7;
int x2 = ++x;
=> x2 is 8 and x is 8
I think it is simplest to understand in terms of the order of evaluation and modification.
(the order of operations is evident in the typed order of the operator and the variable)
I.e. when used in an expression, the postfix operator evaluates and uses the variable's current value in the expression (a return statement or method call) before applying the operator. With the prefix operator it is the other way around.