7

I'm having a hard time understanding what the difference is between incrementing a variable in C# this way:

myInt++;

and

++myInt;

When would ever matter which one you use?

I'll give voteCount++ for the best answer. Or should I give it ++voteCount...

James Van Huis
  • 5,481
  • 1
  • 26
  • 25
Micah
  • 111,873
  • 86
  • 233
  • 325

11 Answers11

53

There is no difference when written on its own (as shown) - in both cases myInt will be incremented by 1.

But there is a difference when you use it in an expression, e.g. something like this:

MyFunction(++myInt);
MyFunction(myInt++);

In the first case, myInt is incremented and the new/incremented value is passed to MyFunction(). In the second case, the old value of myInt is passed to MyFunction() (but myInt is still incremented before the function is called).

Another example is this:

int myInt = 1;
int a = ++myInt;
// myInt is incremented by one and then assigned to a.
// Both myInt and a are now 2.
int b = myInt++;
// myInt is assigned to b and then incremented by one.
// b is now 2, myInt is now 3

BTW: as Don pointed out in a comment the same rules are also valid for decrement operations, and the correct terminology for these operations are:

++i; // pre-increment
i++; // post-increment
--i; // pre-decrement
i--; // post-decrement

As Jon Skeet points out:

Others have shown where it makes a difference, and have commented that as a single statement it doesn't make a difference.

I'd like to add that it's almost always a bad idea to use it where it makes a difference. I suspect there may be some times where it's more readable to have code such as:

Console.WriteLine("Foo: {0}", foo++);

than:

Console.WriteLine("Foo: {0}", foo);
foo++; 

... but they're very rare! The latter of these two samples makes the ordering crystal clear immediately - the former requires a bit of thinking (to my poor brain, anyway). Think of the readability first.

Community
  • 1
  • 1
M4N
  • 94,805
  • 45
  • 217
  • 260
  • ++myInt is usually one instruction faster but this can obviously be optimized by the compiler – Joe Phillips Jan 12 '09 at 21:21
  • are you sure it's incremented after the function is called? i remember having read a thread where they say it's incremented before the call, but the old value is given to the function as argument. it makes diff when myInt is also visible within the function. this would also be the case in c++. – Johannes Schaub - litb Jan 12 '09 at 21:32
  • @litb: you are right, I will update the answer. Thanks a lot. – M4N Jan 12 '09 at 21:37
  • Martin, great u get a +1 :) i don't know why that one guy put Jon's answer into yours without apparently asking you before (after all, Jon got his own nice answer below). but you seem to like it that way. anyway i would ask ppl before i do such things. have fun! – Johannes Schaub - litb Jan 12 '09 at 21:46
  • Just for completeness of this well-explained answer you may want to mention the generally accepted terminology of this, namely pre-increment and post-increment (also you could note that the same applies to decrement x-- vs --x) Good answer. – Don Music Jan 12 '09 at 21:48
  • Jon's answer was added to mine by the question starter. Since it's his question, I won't remove it. But you are right, it doesn't make a lot of sense, since Jon's answer can be found below. – M4N Jan 12 '09 at 21:50
  • I did it because as the question asker I felt it was a valid point, and I wanted a "all encomposing answer". That way anyone reading the question wouldn't have to go all the way to the bottom to find what I consider to be "the rest" of the answer. – Micah Jan 12 '09 at 22:01
  • Micah did what I think the creators of StackOverflow had in mind in the first place - consolidated all the pertinent answers into one and marked it as accepted. Jon still gets his upvotes, but now all the info is in one place for subsequent readers of this question. – Erik Forbes Jan 12 '09 at 22:06
  • Erik, oh ok. that makes sense indeed. didn't notice the guy actually was the original questioner. sorry Micah. have fun too :) – Johannes Schaub - litb Jan 12 '09 at 22:24
  • I'm perfectly happy for my answer to be included here. (The upvotes don't make any difference to me at this time of day anyway, even if that were important to me - but getting a good all-inclusive answer is more important anyway.) – Jon Skeet Jan 12 '09 at 22:26
11

Others have shown where it makes a difference, and have commented that as a single statement it doesn't make a difference.

I'd like to add that it's almost always a bad idea to use it where it makes a difference. I suspect there may be some times where it's more readable to have code such as:

Console.WriteLine("Foo: {0}", foo++);

than:

Console.WriteLine("Foo: {0}", foo);
foo++;

... but they're very rare! The latter of these two samples makes the ordering crystal clear immediately - the former requires a bit of thinking (to my poor brain, anyway). Think of the readability first.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
9

It doesn't unless it is in an expression, i.e.

myInt=1;
x=myInt++;

is different to:

myInt=1;
x=++myInt;

The first assigns 1 to x, because the assignment happens before the increment.

The second assigns 2 to x, because the assignment happens after the increment.

frankodwyer
  • 13,948
  • 9
  • 50
  • 70
6

In assignment or expressions, for example

x = ++myInt; // x = myInt + 1
x = myInt++; // x = myInt

This can also be used in expressions like for loops or if statements. For example take the following where seek is 0 and count is 3.

while(seek++ < count) {
   Console.WriteLine(seek);
}

results in outputs of 1, 2 and 3, for seek, and the following

while(++seek < count) {
   Console.WriteLine(seek);
}

Results in 1 and 2 for seek. So ++myInt increments myInt before its value is evaluated, where as myInt++ is incremented after it is evaluated.

ng.
  • 7,099
  • 1
  • 38
  • 42
4

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
yogman
  • 4,021
  • 4
  • 24
  • 27
  • In general, "in language/compiler X, that I know of", "in language/compiler X only"...? – peSHIr Jan 13 '09 at 10:32
  • As my CS undergraduate-level understanding of the basic concept of the CPU and its registers tells me. I don't know modern CPU instructions. However, I believe there's no CPU instruction in any CPU to increment the value of a memory address by one. – yogman Jan 14 '09 at 04:40
  • 1
    This doesn't really apply to C# – MPritchard Feb 09 '10 at 08:54
3

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
mmmmmmmm
  • 15,269
  • 2
  • 30
  • 55
3

It determines when the result for that operation is returned.

Here's an example from the MSDN site:

static void Main() 
{
    double x;
    x = 1.5;
    Console.WriteLine(++x);
    x = 1.5;
    Console.WriteLine(x++);
    Console.WriteLine(x);
}

And the ouput:

2.5
1.5
2.5
jamesmillerio
  • 3,154
  • 4
  • 27
  • 32
3

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.

jcollum
  • 43,623
  • 55
  • 191
  • 321
3

I think it is simplest to understand in terms of the order of evaluation and modification.

  • The postfix operator (x++) evaluates first and modifies last.
  • The prefix operator (++x) modifies first and evaluates last.

(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.

2

++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
Andrew G. Johnson
  • 26,603
  • 30
  • 91
  • 135
0

If for example you do something like this:

int myInt = 5;

Foo(++myInt);

void Foo(int x)
{
   Console.WriteLine(x);
}

This will print out 6.

Foo(myInt++);

will print out 5;

Basically, ++myInt increments FIRST uses the variable SECOND. myInt++ is the opposite.

BFree
  • 102,548
  • 21
  • 159
  • 201