472,951 Members | 1,910 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,951 software developers and data experts.

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

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 48959
weaknessforcats
9,208 Expert Mod 8TB
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 Expert 2GB
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
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 Expert 512MB
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 Expert 8TB
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 100+
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 100+
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
Thanks, I got it =)

AhmedGY
Jan 26 '08 #9
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
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
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
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
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
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
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
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
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
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
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
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
0
by: Mushico | last post by:
How to calculate date of retirement from date of birth
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...

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.