What is the difference between ++i and i++?
Asked Answered
F

21

1167

In C, what is the difference between using ++i and i++, and which should be used in the incrementation block of a for loop?

Firenze answered 24/8, 2008 at 5:19 Comment(1)
Not sure the original poster is interested, but in C++ the difference in performance can be substantial, since the creation of the temporary object might be expensive for a user defined type.Broderic
T
1430
  • ++i will increment the value of i, and then return the incremented value.

     i = 1;
     j = ++i;
     (i is 2, j is 2)
    
  • i++ will increment the value of i, but return the original value that i held before being incremented.

     i = 1;
     j = i++;
     (i is 2, j is 1)
    

For a for loop, either works. ++i seems more common, perhaps because that is what is used in K&R.

In any case, follow the guideline "prefer ++i over i++" and you won't go wrong.

There's a couple of comments regarding the efficiency of ++i and i++. In any non-student-project compiler, there will be no performance difference. You can verify this by looking at the generated code, which will be identical.

The efficiency question is interesting... here's my attempt at an answer: Is there a performance difference between i++ and ++i in C?

As @OnFreund notes, it's different for a C++ object, since operator++() is a function and the compiler can't know to optimize away the creation of a temporary object to hold the intermediate value.

Tenorrhaphy answered 24/8, 2008 at 5:23 Comment(14)
Won't this effect weather the loop runs once more upon reaching the end condition? For example, for(int i=0; i<10; i++){ print i; } won't this be different than for(int i=0; i<10; ++i){ print i; } My understanding is that some languages will give you different results depending upon which you use.Fiertz
jonnyflash, both will operate identically, since the increment of i and the print are in different statements. This should be the case for any language that supports C-style ++. The only difference between ++i and i++ will be when using the value of the operation in the same statement.Tenorrhaphy
So if you incremented within the loop instead of in the compound for statement it would make a difference, right? Such as for(int i=0; i<10){ print i; ++i;Fiertz
no, since the print and increment are in different statements, the increment can be either ++i or i++. If instead you had print ++i and print i++ the results would be different.Tenorrhaphy
Since in most cases they produce identical code, I prefer i++ because it's of the form "operand-operator", a la an assignment "operand-operator-value". In other words, the target operand is on the left side of the expression, just like it is in an assignment statement.Liberality
@MarkHarrison, it will operate identically not because i++ and print i are in different statements, but because i++; and i<10 are. @jonnyflash's remark is not that off base. Suppose you have for(int i=0; i++<10){ print i; } and for(int i=0; ++i<10){ print i; }. These will operate differently in the way which @johnnyflash described in the first comment.Rotl
++i means increment the value and then use. i++ means use the value and then increment it.Myrna
@ARUN i++ means increment the value, and eval as the value prior to increment. It is the eval result itself, not when the increment happens, that differs. The pre-increment eval result is after the increment, the post-increment eval result is before the increment, but no matter what the increment happens before the eval result is made available. See live example demonstrating as much.Aitken
@sam, because in a typical for loop there is no side effect (for example, assignment) in the ++i part.Tenorrhaphy
I had a doubt on this answer, and have posted a question. I think as the discussion is going on about this answer, you should check it and post what you actually meant: #35644463. Even though it is marked as a dupe, many people are voting to reopen it, with currently 3 reopen votes. I don't think it is a dupe, and it would be helpful if you could clear my doubt.Leveret
I mostly use --i and i-- in a do..while loop. In the first case 0 will not be evaluated inside the loop while in the second case it will.Burr
"Prefer ++i over i++ in for loops" This is contradictory to every modern style-guide I have ever seen.Handmade
Won't this effect weather a while loops? Some languages definitely handle these differently, I was taught the practice of using C++ Style ++ trailing was the consistent method in college but that was 20 years ago... is properly accounting for the iteration of the loop? J=100; I=1;While (J*++I <=500){Print Do something for Five iterations! Currently I = I }; Print Oh Good! Clearly the result I need is I ?Nary
The easiest way to remember ++i from i++ is the position of the ++. One reads "Add then use" while the other reads "Use then add".Fisk
T
249

i++ is known as post increment whereas ++i is called pre increment.

i++

i++ is post increment because it increments i's value by 1 after the operation is over.

Let’s see the following example:

int i = 1, j;
j = i++;

Here value of j = 1, but i = 2. Here the value of i will be assigned to j first, and then i will be incremented.

++i

++i is pre increment because it increments i's value by 1 before the operation. It means j = i; will execute after i++.

Let’s see the following example:

int i = 1, j;
j = ++i;

Here the value of j = 2 but i = 2. Here the value of i will be assigned to j after the i incremention of i. Similarly, ++i will be executed before j=i;.

For your question which should be used in the incrementation block of a for loop? the answer is, you can use any one... It doesn't matter. It will execute your for loop same number of times.

for(i=0; i<5; i++)
   printf("%d ", i);

And

for(i=0; i<5; ++i)
   printf("%d ", i);

Both the loops will produce the same output. I.e., 0 1 2 3 4.

It only matters where you are using it.

for(i = 0; i<5;)
    printf("%d ", ++i);

In this case output will be 1 2 3 4 5.

Tierney answered 28/3, 2012 at 5:54 Comment(0)
B
64

i++: In this scenario first the value is assigned and then increment happens.

++i: In this scenario first the increment is done and then value is assigned

Below is the image visualization and also here is a nice practical video which demonstrates the same.

enter image description here

Bloomery answered 25/7, 2013 at 7:42 Comment(3)
How can you increment somewhat not assigned?Anthropomorphosis
@Anthropomorphosis You can increment a register not assigned to a variable.Stroboscope
You can increment the number without assigning it initially. For instance let i = 0, nums[++i].Ruin
D
57

++i increments the value, then returns it.

i++ returns the value, and then increments it.

It's a subtle difference.

For a for loop, use ++i, as it's slightly faster. i++ will create an extra copy that just gets thrown away.

Ducky answered 24/8, 2008 at 5:21 Comment(2)
I am not aware of any compiler where it does make a difference for integers at least.Warrenne
It is not faster. The values are ignored (only the side effect is effective) and the compiler can/will generate exactly the same code.Emilieemiline
C
51

Please don't worry about the "efficiency" (speed, really) of which one is faster. We have compilers these days that take care of these things. Use whichever one makes sense to use, based on which more clearly shows your intent.

Cf answered 20/9, 2008 at 5:6 Comment(3)
which, I would hope, means 'use prefix (inc|dec)rement unless you actually need the old value prior to the (inc|dec), which very few people do, and yet which a bewildering proportion of supposed teaching materials use, creating a cargo cult of postfix users who don't even know what it is'..!Michaelemichaelina
I'm not sure that "compilers these days ... take care of these things" is universally true. Within a custom operator++(int) (the postfix version) the code pretty much has to create a temporary which will be returned. Are you sure that compilers can always optimize that away?Shagreen
Premature optimization is evil if it adds complexity. However, being curious about which one is faster and using it doesn't add complexity. It's curiosity about the language, and it should be rewarded. It also feels conceptually cleaner to say "Add one and use it" than "Save it somewhere else, add one, and return that saved one". ++i is more desirable potentially in speed and in style. Additionally, a C student doing C++ might like that was taught to him if he wrote i++ on a complex type that can't be removed by the compiler.Fisk
L
47

The only difference is the order of operations between the increment of the variable and the value the operator returns.

This code and its output explains the the difference:

#include<stdio.h>

int main(int argc, char* argv[])
{
  unsigned int i=0, a;
  printf("i initial value: %d; ", i);
  a = i++;
  printf("value returned by i++: %d, i after: %d\n", a, i);
  i=0;
  printf("i initial value: %d; ", i);
  a = ++i;
  printf(" value returned by ++i: %d, i after: %d\n",a, i);
}

The output is:

i initial value: 0; value returned by i++: 0, i after: 1
i initial value: 0;  value returned by ++i: 1, i after: 1

So basically ++i returns the value after it is incremented, while i++ return the value before it is incremented. At the end, in both cases the i will have its value incremented.

Another example:

#include<stdio.h>

int main ()
  int i=0;
  int a = i++*2;
  printf("i=0, i++*2=%d\n", a);
  i=0;
  a = ++i * 2;
  printf("i=0, ++i*2=%d\n", a);
  i=0;
  a = (++i) * 2;
  printf("i=0, (++i)*2=%d\n", a);
  i=0;
  a = (i++) * 2;
  printf("i=0, (i++)*2=%d\n", a);
  return 0;
}

Output:

i=0, i++*2=0
i=0, ++i*2=2
i=0, (++i)*2=2
i=0, (i++)*2=0

Many times there is no difference

Differences are clear when the returned value is assigned to another variable or when the increment is performed in concatenation with other operations where operations precedence is applied (i++*2 is different from ++i*2, as well as (i++)*2 and (++i)*2) in many cases they are interchangeable. A classical example is the for loop syntax:

for(int i=0; i<10; i++)

has the same effect of

for(int i=0; i<10; ++i)

Efficiency

Pre-increment is always at least as efficient as post-increment: in fact post-increment usually involves keeping a copy of the previous value around and might add a little extra code.

As others have suggested, due to compiler optimisations many times they are equally efficient, probably a for loop lies within these cases.

Rule to remember

To not make any confusion between the two operators I adopted this rule:

Associate the position of the operator ++ with respect to the variable i to the order of the ++ operation with respect to the assignment

Said in other words:

  • ++ before i means incrementation must be carried out before assignment;
  • ++ after i means incrementation must be carried out after assignment:
Lipinski answered 27/2, 2019 at 17:49 Comment(3)
'(i++)*2 and (++i)*2 returns the same value' sure???Paintbrush
@YusufR.Karagöz you are absolutely right, thanks for pointing that outLipinski
2. example output also needs to fixedPaintbrush
P
31

The reason ++i can be slightly faster than i++ is that i++ can require a local copy of the value of i before it gets incremented, while ++i never does. In some cases, some compilers will optimize it away if possible... but it's not always possible, and not all compilers do this.

I try not to rely too much on compilers optimizations, so I'd follow Ryan Fox's advice: when I can use both, I use ++i.

Pratincole answered 24/8, 2008 at 6:0 Comment(1)
-1 for C++ answer to C question. There is no more "local copy" of the value of i than there is of the value 1 when you write a statement 1;.Warmedover
H
21

The effective result of using either in a loop is identical. In other words, the loop will do the same exact thing in both instances.

In terms of efficiency, there could be a penalty involved with choosing i++ over ++i. In terms of the language spec, using the post-increment operator should create an extra copy of the value on which the operator is acting. This could be a source of extra operations.

However, you should consider two main problems with the preceding logic.

  1. Modern compilers are great. All good compilers are smart enough to realize that it is seeing an integer increment in a for-loop, and it will optimize both methods to the same efficient code. If using post-increment over pre-increment actually causes your program to have a slower running time, then you are using a terrible compiler.

  2. In terms of operational time-complexity, the two methods (even if a copy is actually being performed) are equivalent. The number of instructions being performed inside of the loop should dominate the number of operations in the increment operation significantly. Therefore, in any loop of significant size, the penalty of the increment method will be massively overshadowed by the execution of the loop body. In other words, you are much better off worrying about optimizing the code in the loop rather than the increment.

In my opinion, the whole issue simply boils down to a style preference. If you think pre-increment is more readable, then use it. Personally, I prefer the post-incrment, but that is probably because it was what I was taught before I knew anything about optimization.

This is a quintessential example of premature optimization, and issues like this have the potential to distract us from serious issues in design. It is still a good question to ask, however, because there is no uniformity in usage or consensus in "best practice."

Humanitarian answered 6/5, 2011 at 21:36 Comment(0)
M
13

++i: is pre-increment the other is post-increment.

i++: gets the element and then increments it.
++i: increments i and then returns the element.

Example:

int i = 0;
printf("i: %d\n", i);
printf("i++: %d\n", i++);
printf("++i: %d\n", ++i);

Output:

i: 0
i++: 0
++i: 2
Marchpast answered 17/9, 2013 at 12:23 Comment(0)
L
12

++i (Prefix operation): Increments and then assigns the value
(eg): int i = 5, int b = ++i In this case, 6 is assigned to b first and then increments to 7 and so on.

i++ (Postfix operation): Assigns and then increments the value
(eg): int i = 5, int b = i++ In this case, 5 is assigned to b first and then increments to 6 and so on.

Incase of for loop: i++ is mostly used because, normally we use the starting value of i before incrementing in for loop. But depending on your program logic it may vary.

Longish answered 13/5, 2016 at 5:50 Comment(1)
Last statement seems wrong, ++i and i++ work the same way in a for loop, but your sentence suggests otherwise.Representation
B
10

i++ and ++i

This little code may help to visualize the difference from a different angle than the already posted answers:

int i = 10, j = 10;
  
printf ("i is %i \n", i);
printf ("i++ is %i \n", i++);
printf ("i is %i \n\n", i);
  
printf ("j is %i \n", j);
printf ("++j is %i \n", ++j);
printf ("j is %i \n", j);

The outcome is:

//Remember that the values are i = 10, and j = 10

i is 10 
i++ is 10     //Assigns (print out), then increments
i is 11 

j is 10 
++j is 11    //Increments, then assigns (print out)
j is 11 

Pay attention to the before and after situations.

for loop

As for which one of them should be used in an incrementation block of a for loop, I think that the best we can do to make a decision is use a good example:

int i, j;

for (i = 0; i <= 3; i++)
    printf (" > iteration #%i", i);

printf ("\n");

for (j = 0; j <= 3; ++j)
    printf (" > iteration #%i", j);

The outcome is:

> iteration #0 > iteration #1 > iteration #2 > iteration #3
> iteration #0 > iteration #1 > iteration #2 > iteration #3 

I don't know about you, but I don't see any difference in its usage, at least in a for loop.

Broadcasting answered 19/2, 2018 at 20:51 Comment(0)
U
9

The following C code fragment illustrates the difference between the pre and post increment and decrement operators:

int  i;
int  j;

Increment operators:

i = 1;
j = ++i;    // i is now 2, j is also 2
j = i++;    // i is now 3, j is 2
Unjust answered 1/10, 2017 at 15:58 Comment(0)
H
8

Shortly:

++i and i++ works same if you are not writing them in a function. If you use something like function(i++) or function(++i) you can see the difference.

function(++i) says first increment i by 1, after that put this i into the function with new value.

function(i++) says put first i into the function after that increment i by 1.

int i=4;
printf("%d\n",pow(++i,2));//it prints 25 and i is 5 now
i=4;
printf("%d",pow(i++,2));//it prints 16 i is 5 now
Hyperthyroidism answered 22/8, 2013 at 17:25 Comment(1)
The difference is not really tied to function calls (and you can spot the difference without making function calls). There's a difference between int j = ++i; and int k = i++; even when there's no function call involved.Hemocyte
R
8

Pre-crement means increment on the same line. Post-increment means increment after the line executes.

int j = 0;
System.out.println(j); // 0
System.out.println(j++); // 0. post-increment. It means after this line executes j increments.

int k = 0;
System.out.println(k); // 0
System.out.println(++k); // 1. pre increment. It means it increments first and then the line executes

When it comes with OR, AND operators, it becomes more interesting.

int m = 0;
if((m == 0 || m++ == 0) && (m++ == 1)) { // False
    // In the OR condition, if the first line is already true
    // then the compiler doesn't check the rest. It is a
    // technique of compiler optimization
    System.out.println("post-increment " + m);
}

int n = 0;
if((n == 0 || n++ == 0) && (++n == 1)) { // True
    System.out.println("pre-increment " + n); // 1
}

In Array

System.out.println("In Array");
int[] a = { 55, 11, 15, 20, 25 };
int ii, jj, kk = 1, mm;
ii = ++a[1]; // ii = 12. a[1] = a[1] + 1
System.out.println(a[1]); // 12

jj = a[1]++; // 12
System.out.println(a[1]); // a[1] = 13

mm = a[1]; // 13
System.out.printf("\n%d %d %d\n", ii, jj, mm); // 12, 12, 13

for (int val: a) {
     System.out.print(" " + val); // 55, 13, 15, 20, 25
}

In C++ post/pre-increment of pointer variable

#include <iostream>
using namespace std;

int main() {

    int x = 10;
    int* p = &x;

    std::cout << "address = " << p <<"\n"; // Prints the address of x
    std::cout << "address = " << p <<"\n"; // Prints (the address of x) + sizeof(int)
    std::cout << "address = " << &x <<"\n"; // Prints the address of x

    std::cout << "address = " << ++&x << "\n"; // Error. The reference can't reassign, because it is fixed (immutable).
}
Ransdell answered 29/9, 2017 at 16:49 Comment(0)
B
8

In simple words the difference between both is in the steps take a look to the image below.

enter image description here

Example:

int i = 1;
int j = i++;

The j result is 1

int i = 1;
int j = ++i;

The j result is 2

Note: in both cases i values is 2

Blown answered 11/1, 2022 at 18:21 Comment(0)
H
6

I assume you understand the difference in semantics now (though honestly I wonder why people ask 'what does operator X mean' questions on stack overflow rather than reading, you know, a book or web tutorial or something.

But anyway, as far as which one to use, ignore questions of performance, which are unlikely important even in C++. This is the principle you should use when deciding which to use:

Say what you mean in code.

If you don't need the value-before-increment in your statement, don't use that form of the operator. It's a minor issue, but unless you are working with a style guide that bans one version in favor of the other altogether (aka a bone-headed style guide), you should use the form that most exactly expresses what you are trying to do.

QED, use the pre-increment version:

for (int i = 0; i != X; ++i) ...
Herculean answered 4/8, 2011 at 17:20 Comment(0)
F
6

The Main Difference is

  • i++ Post(After Increment) and
  • ++i Pre (Before Increment)

    • post if i =1 the loop increments like 1,2,3,4,n
    • pre if i =1 the loop increments like 2,3,4,5,n
Failing answered 13/5, 2016 at 6:0 Comment(0)
A
6

The difference can be understood by this simple C++ code below:

int i, j, k, l;
i = 1; //initialize int i with 1
j = i+1; //add 1 with i and set that as the value of j. i is still 1
k = i++; //k gets the current value of i, after that i is incremented. So here i is 2, but k is 1
l = ++i; // i is incremented first and then returned. So the value of i is 3 and so does l.
cout << i << ' ' << j << ' ' << k << ' '<< l << endl;
return 0;
Articulation answered 12/9, 2017 at 21:13 Comment(0)
I
2

You can think of the internal conversion of that as multiple statements:

// case 1

i++;

/* you can think as,
 * i;
 * i= i+1;
 */



// case 2

++i;

/* you can think as,
 * i = i+i;
 * i;
 */
Io answered 6/8, 2018 at 9:25 Comment(1)
Case 2 suggests that ++i increments i by i. This is wrong! See the other answers for the correct solution (e.g. this one https://mcmap.net/q/23953/-what-is-the-difference-between-i-and-i ).Ludly
N
0

To add some more clarity:

This ++ operator overloading explains how pre/postfix increment can be done and then you'll get the difference between the prefix and the postfix ++ operators.

class Int {
    private:
        int i;

    public:
        Int(int i)
        {
            this->i = i;
        }

        // Overloading the prefix operator
        Int& operator++()
        {
            ++i;
            // returned value should be a reference to *this
            return *this;
        }

        // Overloading the postfix operator
        Int operator++(int)
        {
            // returned value should be a copy of the object before increment
            Int obj = *this;
            ++i;
            return obj;
        }
};
Neil answered 4/2 at 14:23 Comment(0)
B
-2

a=i++ means a contains the current i value.

a=++i means a contains the incremented i value.

Brouhaha answered 22/1, 2013 at 9:13 Comment(1)
This answer isn't accurate. a = i++; means the value stored in a will be the value of i before the increment, but 'without incrementing' implies that i is not incremented, which is completely wrong — i is incremented, but the value of the expression is the value before the increment.Hemocyte

© 2022 - 2024 — McMap. All rights reserved.