473,498 Members | 1,972 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Difference between i++ and ++i in for loop

9 New Member
I know the difference between the prefix/postfix increment, the prefix returns the value after increment, while postfix return it before increment, however i can't see any difference when using FOR loops.

see:

for(int i=0;i<10;i++)
printf("%d",i);
//prints i=0 and update i++, but since its postfix increment, it's supposed to return the value of i which = 0 and then increment to 1, if thats the case, it will print i = 0 in an infinite loop, because the i never get to 1 since i++ returns the i before increment (0), However the loop works normal and print from 0 to 9, i dont understand why.

Here:

for(int i=0;i<10;++i)
printf("%d",i);
//prints i=0 and then update ++i and returns i=1, and so on.

Can someone explain the difference between i++ and ++i in for loops?

Thanks,

AhmedGY
Jan 25 '08 #1
9 49499
weaknessforcats
9,208 Recognized Expert Moderator Expert
In your example there is no logical difference. That is:
Expand|Select|Wrap|Line Numbers
  1. ++i;
  2. i++;
  3.  
do the same thing. i is incremented.

The difference is that with prefix (++i) the variable is incremented and then used whereas postfix (i++) the variable is used and then incrmented.

You see the difference here:

Expand|Select|Wrap|Line Numbers
  1. int i = 5;
  2. if (++i == 6)
  3. {
  4.  
  5. }
  6.  
Here is a prefix increment. i is incremented to 6 and then used. 6 == 6 and the statement is true.

Expand|Select|Wrap|Line Numbers
  1. int i = 5;
  2. if (i++ == 6)
  3. {
  4.  
  5. }
  6.  
Here is a postfix incrment. i is used 5 == 6 (then the i is incrmented) and th statement is false.

In both cases, after the if statement, i is 6.
Jan 25 '08 #2
Ganon11
3,652 Recognized Expert Specialist
It doesn't make a huge difference in timing, but I believe using the pre-increment operator in a for...loop is slightly faster. Both pre-increment and post-increment operations increment the operand, but the post-increment operator (i++) must first make a copy of the old value, then increment and return the old value. The pre-increment operator (++i) merely increments and returns. You won't see a large return on a small for loop, such as one that runs 10 times, but you may see a gain in time on a very large loop, or one that using objects such as iterators rather than integers.

The reason there is no logical difference between i++ and ++i in the loop is because the update statement is a statement of its own. In other words, say you have a simple for loop, like this:

Expand|Select|Wrap|Line Numbers
  1. for (int i = 0; i < 20; i++) {
  2.   // Blah blah blah.
  3. }
This could be rewritten as:

Expand|Select|Wrap|Line Numbers
  1. int i = 0;
  2. while (i < 20) {
  3.   // Blah blah blah.
  4.   i++;
  5. }
As you can see, each section of the for loop header serves a different purpose. In general, the pattern is:

Expand|Select|Wrap|Line Numbers
  1. for (/* Initialization statement */; /* Continuation Check */; /* Update statement */) {
  2.   // Blah blah blah.
  3. }
and can always be rewritten as

Expand|Select|Wrap|Line Numbers
  1. /* Initialization statement */
  2. while (/* Continuation Check */) {
  3.   // Blah blah blah.
  4.   /* Update statement */
  5. }
So, when your update statement is i++ or ++i, they are treated as a separate statement, and as you seem to know, there is functionally no difference between the statement

i++;

and the statement

++i;

on their own.
Jan 25 '08 #3
AhmedGY
9 New Member
but the post-increment operator (i++) must first make a copy of the old value, then increment and return the old value.
return the old value to where?, as far as i know the update statement return the value to the continuation check, so using i++ will return the old value (which is 0), then increment, lets trace the i in this example:


Expand|Select|Wrap|Line Numbers
  1. for (int i = 0; i < 10; i++) 
  2.       {
  3.           printf("%d\n",i);
  4.       }
i=0 and <10, go inside the loop and print 0, the update statement i++ makes a copy of the value 0 return it back to continouation check and increment i by 1, the old value 0 that been returned should now go inside the loop again and print another 0.

thats how i logically understand the things going on, correct me please.
Jan 25 '08 #4
oler1s
671 Recognized Expert Contributor
as far as i know the update statement return the value to the continuation check, so using i++ will return the old value (which is 0), then increment,
Careful about how you interpret the for loop. The update in the for loop doesn't mean you set the value of i for the entire for loop. Evaluating a value there has no meaning, because the for loop goes through another iteration regardless. The only thing that matters is the side effect (like incrementing).

i=0 and <10, go inside the loop and print 0, the update statement i++ makes a copy of the value 0 return it back to continouation check and increment i by 1,
The evaluating to 0 is meaningless. What is meaningful is incrementing i by 1.

the old value 0 that been returned should now go inside the loop again
Huh? How does this compute? The for loop is not like a function, where i gets passed into it. The fact that i++ returns 0 is utterly meaningless. That value for i is not used at all. i gets incremented by 1, so the new value of i is used on the next iteration of the for loop.

In a for loop, i++ and ++i shouldn't make a difference. It shouldn't make a difference in speed either, unless the compiler is really, really bad.
Jan 26 '08 #5
JosAH
11,448 Recognized Expert MVP
It doesn't make a huge difference in timing, but I believe using the pre-increment operator in a for...loop is slightly faster. Both pre-increment and post-increment operations increment the operand, but the post-increment operator (i++) must first make a copy of the old value, then increment and return the old value. The pre-increment operator (++i) merely increments and returns.
That is all highly dependent on the target processor; e.g. Sun's SPARC processor
always executes the instruction *following* a conditional branch, no matter the
result of the branch condition. The gcc code generator cleverly 'hides' the increment
instruction there effectively speeding up the post-increment/decrement instruction.

I bet other processors implement different tricks to make a pre-increment/decrement
instruction faster than the other one; but remember: not the entire world uses Intel
processors ...

kind regards,

Jos
Jan 26 '08 #6
hsn
237 New Member
i=5;
if you said i++, i will be 6 in the next line;
but if you said ++i right away it will be 6;

Good luck
Jan 26 '08 #7
hsn
237 New Member
sorry i have posted a wrong point

if i=5
if you used i++ i a for loop i will be 6 in the end of the loop. same point for if statement.
but the post about the ++i is correct

good luck again

hsn
Jan 26 '08 #8
AhmedGY
9 New Member
Thanks, I got it =)

AhmedGY
Jan 26 '08 #9
varun53
1 New Member
Expand|Select|Wrap|Line Numbers
  1. for(initialization;condition;incre/decre)
in this statement, at first initialization executes, then condition executes, now this is where you have to understand...that is after condition, the body of the look executes and finally incre/decre takes place...after incre/decre, the condition again is checked and the body is executed and goes on....

this is the simple reason that there is no difference between pre increment and post-increment in for loop.....ta...da...
Jun 14 '14 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

12
4870
by: reynoldscraigr | last post by:
Hi All, hope someone can see what wrong here I have the following function function RemoveMenuFromHoldArray(menuName) { var i = 0; for (i=0;i<=MenusToHoldOpen.length-1;i++) { if...
7
3189
by: Mahesh Kumar Reddy.R | last post by:
Hi Can any body resolve this.. In what cases one of the loop constructs better than other interms of speed , space and any other (redability). thanks mahesh
8
2998
by: Dave Veeneman | last post by:
In a for-loop, is a calculated expression re-calculated on each pass through the loop, or only once, when the loop is initialized? For example, assume the following loop: for (int i = 0; i <...
21
2812
by: Rich | last post by:
I was considering C# for developing a scientific application, but I have noticed a ~30% difference between VC++ .NET and C# on the same machine, under identical conditions: double a = 0,b = 0, c...
6
71927
by: John Pass | last post by:
What is the difference between a While and Do While/Loop repetition structure. If they is no difference (as it seems) why do both exist?
4
2852
by: Uday Bidkar | last post by:
I am trying to register my interface with IConnectionPoint of outlook reminders to capture some Outlook Reminder events and having some issues. Here goes the pseudo code int APIENTRY...
6
2442
by: vlsidesign | last post by:
If I have a "for" loop like this: for (i = 0; i < 10; i++) or like this for (i = 0; i < 10; ++i) both of the "for" loops will function the same. I also noticed if I use a variable called j...
3
33331
by: Akira | last post by:
I noticed that using foreach is much slower than using for-loop, so I want to change our current code from foreach to for-loop. But I can't figure out how. Could someone help me please? Current...
10
2292
by: rohitjogya | last post by:
Can anyone tell me the difference bet for loop and while loop execution? ____________________ for (i=0 ; i<10 ; i++) ; /* Do nothing*/ print i; ___________________ i=0;
3
1794
by: cheguashwini | last post by:
Hi I have a problem. I have two tables...table1 and table2. table1 has the column latitude and sno(serial number) and table2 has the column lat and sno(serial number) . i have to find the...
0
7125
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7167
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7208
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6890
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5464
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
4915
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4593
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3085
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
292
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.