473,461 Members | 1,426 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

why i++ instead of ++i in for loops


I have been reading various texts in C/ C++ and Java. The for lops all
run along the lines of :

int i ;

for(i = 0 ; i < 4 ; i++)

{

.....

}

I understand the difference between ++i and i++, but I can not see why
i++ is used in these loops when, as I understand it, the steping
expression would be more alined to i = i + 1 in this type of case. The
logic of i++ is not the same. The final result might but the evaluation
process is not.

Ok I realise at the end of the loop the value of i is the same which
ever method you use. But that does not explaine why the preference.

Also from what I can see at the assembly code level

int i ;

for(i = 0 ; i < 4 ; ++i)

{

.....

}

and

int i ;

for(i = 0 ; i < 4 ; i++)

{

.....

}

are exactly the same.

Could some please explain the need to use i++ over ++i.
--
Posted via http://dbforums.com
Jul 19 '05 #1
17 72925
* snip *
Could some please explain the need to use i++ over ++i.


Strictly speaking there is no real need for i++, since "int x = i;
++i;" yields the same result as "int x = i++;". As you have noticed in
for loops with int as loop variable using ++i or i++ doesn't make a
difference with most compilers. Note that with iterators the ++i version
may very well be more efficient than i++.

--
Peter van Merkerk
peter.van.merkerk(at)dse.nl


Jul 19 '05 #2
newtothis wrote:

I have been reading various texts in C/ C++ and Java. The for lops all
run along the lines of :

int i ;

for(i = 0 ; i < 4 ; i++)

{

....

}

I understand the difference between ++i and i++, but I can not see why
i++ is used in these loops when, as I understand it, the steping
expression would be more alined to i = i + 1 in this type of case. The
logic of i++ is not the same. The final result might but the
evaluation process is not.


For builtin types, it really doesn't matter. But in C++, you can write
and operator++ for your own class. And then it might matter, becaure
postfix ++ has to create a copy of the object so that the old value can
be returned. If you don't need the return value, that copy is
unnecessary. If the compiler doesn't do named return value
optimization, that copy might even need to be copied again, and all
that just to throw the result away. The postfix operator++ for an own
class might look something like this:

MyClass MyClass::operator++(int)
{
MyClass retval(*this); // copy the object
// do whatever is needed to "increment" the object
reutrn retval; // return the copy by value
}

while prefix ++ might look like:

MyClass& MyClass::operator++()
{
// do whatever is needed to "increment" the object
return *this; // return a refernce to the object
}

Therefore, it's considered a good habit to always use prefix ++ if the
return value is not needed.
Jul 19 '05 #3
newtothis wrote:
I have been reading various texts in C/ C++ and Java. The for lops all
run along the lines of :

int i ;

for(i = 0 ; i < 4 ; i++)

{
....
}

I understand the difference between ++i and i++, but I can not see why
i++ is used in these loops when, as I understand it, the steping
expression would be more alined to i = i + 1 in this type of case. The
logic of i++ is not the same. The final result might but the evaluation
process is not.
Good call, "newtothis"!

Ok I realise at the end of the loop the value of i is the same which
ever method you use. But that does not explaine why the preference.

Also from what I can see at the assembly code level

int i ;

for(i = 0 ; i < 4 ; ++i)
{
....
}

and

int i ;

for(i = 0 ; i < 4 ; i++)
{
....
}

are exactly the same.
Which, by itself is irrelevant -- and only because a compiler can see
that the return value of `i++', i.e. the original value of `i' is
thrown
away.
Could some please explain the need to use i++ over ++i.
Sorry. Can't be done. ;-) There is no `need'.
What there *is* is `force of habit'. Historical artifact. Custom. Idiom.

While it is true that there is likely to be no difference in the
generated code when dealing with basic types, there often *is* a
difference -- and a potentially significant one -- when dealing with
user defined types (where `++', prefix and postfix are overloaded
operators).

Again, good call. Using the prefix form in such loops is to be
preferred -- it's just a hard habit to break!

HTH,
--ag

--
Posted via http://dbforums.com


--
Artie Gold -- Austin, Texas
Oh, for the good old days of regular old SPAM.

Jul 19 '05 #4
> I have been reading various texts in C/ C++ and Java. The for lops all
run along the lines of : int i ; for(i = 0 ; i < 4 ; i++) { .... } I understand the difference between ++i and i++, but I can not see why
i++ is used in these loops when, as I understand it, the steping
expression would be more alined to i = i + 1 in this type of case. The
logic of i++ is not the same. The final result might but the evaluation
process is not. Ok I realise at the end of the loop the value of i is the same which
ever method you use. But that does not explaine why the preference.


You have hit on one of the reasons that "Accelerated C++" always uses the
"++i" form unless something is going to be done with the value of the
expression. So, for example, we would write

++i;

instead of

i++;

but we would write

n = a[i++];

if it were appropriate to do so--the point being that the value of "i++" is
used in the second example.

Incidentally, instead of

for (i = 0; i < 4; i++)

we would write

for (i = 0; i != 4; ++i)

because that way, we can use the same general form of loop for all kinds of
iterators in addition to integers.
Jul 19 '05 #5

"newtothis" <me*********@dbforums.com> wrote in message
news:35****************@dbforums.com...

I understand the difference between ++i and i++, but I can not see why
i++ is used in these loops when, as I understand it, the steping
expression would be more alined to i = i + 1 in this type of case. The
logic of i++ is not the same. The final result might but the evaluation
process is not.
Ok I realise at the end of the loop the value of i is the same which
ever method you use. But that does not explaine why the preference.


I think you've answered your own question. In that case, the result is the
same so it really doesn't matter. If it doesn't matter, i++ seems more
aesthetically pleasing to most people, since logically you see the variable
first, and then you see what to do with it. If these were classes with
member functions, it would look like this.

Int i(1);
i.increment();
vs.
increment().i;

The first looks more natural.
Jul 19 '05 #6

"Andrew Koenig" <ar*@acm.org> wrote in message
news:3x***********************@bgtnsc04-news.ops.worldnet.att.net...
...So, for example, we would write

++i;

instead of

i++;

but we would write

n = a[i++];

if it were appropriate to do so--the point being that the value of "i++" is used in the second example.


What do you mean that "the value of "i++" is used in the second example"?
If you're referring to n = a[i++], then the value that is used to index into
a is i, not i++. The increment is done afterwards. If, instead, you're
just saying that you should only use i++ when you need the value of i++,
again, I don't see how you can get that value, except in a following
statement, as in

x = a[i++];
n = a[i]; // here we use the incremented value of i

I think I see what you were getting at, but your phrasing is a little
confusing.

-Howard


Jul 19 '05 #7
Howard wrote:

"Andrew Koenig" <ar*@acm.org> wrote in message
news:3x***********************@bgtnsc04-news.ops.worldnet.att.net...
...So, for example, we would write

++i;

instead of

i++;

but we would write

n = a[i++];

if it were appropriate to do so--the point being that the value of
"i++" is
used in the second example.


What do you mean that "the value of "i++" is used in the second
example"? If you're referring to n = a[i++], then the value that is
used to index into a is i, not i++.


i and i++ have the same value. The value of postfix++ is the value that
the operand had before the increment.
The increment is done afterwards.
Right.
If, instead, you're just saying that you should only use i++ when you
need the value of i++, again, I don't see how you can get that value,
int a = i++;

now a has the value of i++.
except in a following statement, as in

x = a[i++];
n = a[i]; // here we use the incremented value of i

I think I see what you were getting at, but your phrasing is a little
confusing.


You seem to be confused by the term "value of i++". The value of i++ is
what you get when you e.g. assign "i++" to something, not the value of
i after i++ has been executed.

Jul 19 '05 #8
> > ...So, for example, we would write

++i;

instead of

i++;

but we would write

n = a[i++];

if it were appropriate to do so--the point being that the value of "i++"
is used in the second example.

What do you mean that "the value of "i++" is used in the second example"?
If you're referring to n = a[i++], then the value that is used to index

into a is i, not i++.


I meant exactly what I said: The value of i++ is used in the second
example. Now, as it happens, if i is an integer, then the value of i++ is a
copy of what the value of i was before i was incremented. If i is a
user-defined type, the value of i++ might be something different. Either
way, evaluating the expression a[i++] involves using the value of i++.
Jul 19 '05 #9

"Rolf Magnus" <ra******@t-online.de> wrote in message
news:bn*************@news.t-online.com...
Howard wrote:

"Andrew Koenig" <ar*@acm.org> wrote in message
news:3x***********************@bgtnsc04-news.ops.worldnet.att.net...
...So, for example, we would write

++i;

instead of

i++;

but we would write

n = a[i++];

if it were appropriate to do so--the point being that the value of
"i++"

is
used in the second example.


What do you mean that "the value of "i++" is used in the second
example"? If you're referring to n = a[i++], then the value that is
used to index into a is i, not i++.


i and i++ have the same value. The value of postfix++ is the value that
the operand had before the increment.
The increment is done afterwards.


Right.
If, instead, you're just saying that you should only use i++ when you
need the value of i++, again, I don't see how you can get that value,


int a = i++;

now a has the value of i++.
except in a following statement, as in

x = a[i++];
n = a[i]; // here we use the incremented value of i

I think I see what you were getting at, but your phrasing is a little
confusing.


You seem to be confused by the term "value of i++". The value of i++ is
what you get when you e.g. assign "i++" to something, not the value of
i after i++ has been executed.


That's exactly where I was confused. Which is why I asked what he meant by
"the value of i++".

It seems very strange to refer to the "value of i++" unless you were
refering to the value you get by performing the ++ operation upon the i
variable, which is obviously not the intent. To me, it would be like
referring to the "value of 7+1", and intending to refer to the value 7
(before adding one), whereas in normal conversation, you'd be talking about
the value 8, which is what 7+1 is equal to. See why it's confusing (at
least to me)?

No argument here on the "truth" of what Andrew said...just confusion on the
terminology.

-Howard


Jul 19 '05 #10
Howard wrote:

"Rolf Magnus" <ra******@t-online.de> wrote in message
news:bn*************@news.t-online.com...
Howard wrote:
>
> "Andrew Koenig" <ar*@acm.org> wrote in message
> news:3xvnb.19740 $0***********@bgtnsc04-news.ops.worldnet.att.net... >
>> ...So, for example, we would write
>>
>> ++i;
>>
>> instead of
>>
>> i++;
>>
>> but we would write
>>
>> n = a[i++];
>>
>> if it were appropriate to do so--the point being that the value of
>> "i++"
> is
>> used in the second example.
>>
>
> What do you mean that "the value of "i++" is used in the second
> example"? If you're referring to n = a[i++], then the value that is
> used to index into a is i, not i++.


i and i++ have the same value. The value of postfix++ is the value
that the operand had before the increment.
> The increment is done afterwards.


Right.
> If, instead, you're just saying that you should only use i++ when
> you need the value of i++, again, I don't see how you can get that
> value,


int a = i++;

now a has the value of i++.
> except in a following statement, as in
>
> x = a[i++];
> n = a[i]; // here we use the incremented value of i
>
> I think I see what you were getting at, but your phrasing is a
> little confusing.


You seem to be confused by the term "value of i++". The value of i++
is what you get when you e.g. assign "i++" to something, not the
value of i after i++ has been executed.


That's exactly where I was confused. Which is why I asked what he
meant by "the value of i++".

It seems very strange to refer to the "value of i++" unless you were
refering to the value you get by performing the ++ operation upon the
i
variable, which is obviously not the intent. To me, it would be like
referring to the "value of 7+1", and intending to refer to the value 7
(before adding one), whereas in normal conversation, you'd be talking
about
the value 8, which is what 7+1 is equal to. See why it's confusing
(at least to me)?


Seems logical to me:

int x = 3 + 1;

the value of 3 + 1 is 4, so x is set to 4.

int y = x;

the value of x is 4, so y is set to 4.

int f(int i)
{
return i+1;
}

y = f(x);

the value of f(x) is 5, so y is set to 5 now.

int g(int& i)
{
int retval = i;
++i;
return retval;
}

y = g(x);

the value of g(x) is 4, so y is set to 4.

z = x++;

the value of x++ is 5, so z is set to 5 now.

Jul 19 '05 #11

"Rolf Magnus" <ra******@t-online.de> wrote in message
news:bn*************@news.t-online.com...
Seems logical to me:


Oh well. I find it confusing, you don't. We'll both live. :-)

-Howard


Jul 19 '05 #12

So from what has been said, except for may be the situation of an
oveloaded operator, the only reason for ++i vs i++ in the for loop is
programmer preference.

This then is close to the arguments of underscore vs mixedcase
vqariables.

Personal preference.

Why then dont the writeres of texts explain this instead of trying to
lay down some form of undefinable law?

Thanks for these comments as it clears up some programming "rules"
people have tried to push on me.
--
Posted via http://dbforums.com
Jul 19 '05 #13
I think you've answered your own question. In that case, the result is the same so it really doesn't matter. If it doesn't matter, i++ seems more
aesthetically pleasing to most people, since logically you see the variable first, and then you see what to do with it. If these were classes with
member functions, it would look like this.


Actually that's not true. i++ has to create a temporary and ++i doesn't.
This may
not be a big deal when i is an int, but it gets pretty inefficient when i is
a larger type or
an iterator etc.
Jul 19 '05 #14
> So from what has been said, except for may be the situation of an
oveloaded operator, the only reason for ++i vs i++ in the for loop is
programmer preference.
Not quite. There's no difference in practice if i is an integer variable,
but if it's an iterator, there may be a performance difference. There is
also the philosophical question of whether it's a good thing to ask the
machine to do work that you know is going to be discarded.
Why then dont the writeres of texts explain this instead of trying to
lay down some form of undefinable law?


Some of them do.
Jul 19 '05 #15
newtothis <me*********@dbforums.com> wrote in message news:<35****************@dbforums.com>...
So from what has been said, except for may be the situation of an
oveloaded operator, the only reason for ++i vs i++ in the for loop is
programmer preference.
Yes.

This then is close to the arguments of underscore vs mixedcase
vqariables.
Not at all. In situations as the one you mentioned, you usually
acquire a habit of either writing i++ or ++i. If you write ++i you are
assured of optimal performance, if you write i++, you're not. Thus you
should always prefer the ++i version.
Personal preference.

Why then dont the writeres of texts explain this instead of trying to
lay down some form of undefinable law?
I do believe that most good textbooks will tell you that you should
prefer ++i. At least they ought to do so.

Thanks for these comments as it clears up some programming "rules"
people have tried to push on me.


Kind regards
Peter Koch Larsen
Jul 19 '05 #16

Thanks for all the comments. I did not intend to cause a general stir.
This though has confirmed that my use of ++i, when appropiate, in such
loops has been correct.

I realise at times the use of i++ is appropiate and is dependent on the
intent of the design and code.

I now just have to get over the issues of mixed case or underscores in
variables. That seems to have been discussed at some length anyway.

Thanks again

Newtothis
--
Posted via http://dbforums.com
Jul 19 '05 #17

"Duane Hebert" <sp**@flarn2.com> wrote in message
news:9C*********************@weber.videotron.net.. .
I think you've answered your own question. In that case, the result is

the
same so it really doesn't matter. If it doesn't matter, i++ seems more
aesthetically pleasing to most people, since logically you see the

variable
first, and then you see what to do with it. If these were classes with
member functions, it would look like this.


Actually that's not true.


What's not true?
Jul 19 '05 #18

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
by: Alf P. Steinbach | last post by:
The third part of my attempted Correct C++ tutorial is now available, although for now only in Word format (use free Open Office if no Word), and also, it's not yet been extensively reviewed -- ...
8
by: vijay | last post by:
Hello, What happens to float variable in loops. For example, float f=8.7; if(f<8.7) printf("less"); else if(f==8.7) printf("equal"); else if(f>8.7)
109
by: Neo | last post by:
Hi Folks,http://www.abarnett.demon.co.uk/tutorial.html#FASTFOR Page states:for( i=0; i<10; i++){ ... }i loops through the values 0,1,2,3,4,5,6,7,8,9 If you don't care about the order of the loop...
6
by: Ian Ribas | last post by:
Hello, This is probably a common problem, but I couldn't really find a direct answer in the archives (or maybe just couldn't find one that satisfied me ;-). I created an index specifically to...
6
by: Scott Brady Drummonds | last post by:
Hi, everyone, I was in a code review a couple of days ago and noticed one of my coworkers never used for() loops. Instead, he would use while() loops such as the following: i = 0; while (i...
17
by: John Salerno | last post by:
I'm reading Text Processing in Python right now and I came across a comment that is helping me to see for loops in a new light. I think because I'm used to the C-style for loop where you create a...
2
by: bitong | last post by:
I'm a little bit confuse with regard to our subject in C..We are now with the Loops..and I was just wondering if given a problem, can you use Do-while loops instead of a for loops or vise versa? are...
32
by: lovecreatesbea... | last post by:
In C++ Primer 4th, sec 3.3.2, it states that C++ programmers use != rather than < in a for loop. The following small snippet erases punctuations in a string. It works well with < used in the for...
17
by: Gandalf | last post by:
how can I do width python a normal for loop width tree conditions like for example : for x=1;x<=100;x+x: print x thanks
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
1
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
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
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
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

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.