Re: for loop i++ or ++i
From: Michael C# (xyz_at_yomomma.com)
Date: 03/24/05
- Next message: oj: "Re: NT AUTHORITY\ANONYMOUS LOGON --- SQL server"
- Previous message: Vlad: "Re: Creating an RSS Feed"
- In reply to: Brian: "for loop i++ or ++i"
- Next in thread: Brian: "Re: for loop i++ or ++i"
- Reply: Brian: "Re: for loop i++ or ++i"
- Messages sorted by: [ date ] [ thread ]
Date: Thu, 24 Mar 2005 14:45:26 -0500
Think of your for loop in these terms. It's roughly equivalent to a while
loop and an assignment statement:
int i = 0;
while (i < 9)
{
...
i++;
}
OR
int i = 0;
while (i < 9)
{
...
++i;
}
As you can see, the increment operator occurs at the end of the while loop.
The effects on placement of ++ is more readily apparent in this example:
int i = 0;
// Assigns the value of i to j
// THEN increments i
int j = i++;
Console.WriteLine(j);
i = 0;
// Increments i, then assigns the
// value if i to j
j = ++i;
Console.WriteLine(j);
Thanks.
"Brian" <fake@email.com> wrote in message
news:4021632472603527812500@news.microsoft.com...
> It's a minor thing, but I'm confused on the increment operator in a for
> loop.
>
> I think most usually write:
>
> for (int i = 0; i < something; i++)
> {
> ...
> }
>
> But, in my book (from MSPress) it shows:
>
> for (int i; i < something; ++i)
> {
> ...
> }
>
>
> From what I remember in my readings, the ++i is supposed to be faster,
> performance wise.
>
> As far as results, they both seem to do the same thing in a loop.
> In my tests, of "for (int i = 0, i < 9, ++i OR i++)", both loops iterated
> from 0 to 9.
>
> But, in reading up on the increment operator on MSDN:
>
> ++i = The result of the operation is the value of the operand after it has
> been incremented.
>
> i++ = The result of the operation is the value of the operand before it
> has been incremented.
>
> This doesn't seem to make sense. If ++i returns the value after it has
> been incremented, then if i was initilized to 0, should the first loop in
> the for loop have i = 1????
>
> --Brian
>
>
>
>
- Next message: oj: "Re: NT AUTHORITY\ANONYMOUS LOGON --- SQL server"
- Previous message: Vlad: "Re: Creating an RSS Feed"
- In reply to: Brian: "for loop i++ or ++i"
- Next in thread: Brian: "Re: for loop i++ or ++i"
- Reply: Brian: "Re: for loop i++ or ++i"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|