Re: Funny loop with post-increment.
Frans Bouma <[email protected]> Tue, 19 Feb 2008 09:44:18 +0100
| Newsgroups | gmane.comp.windows.devel.dotnet.clr |
|---|---|
| Message-ID | <009201c872d3$9d840500$d88c0f00$@nl> |
> Don't forget that this is a POST-increment. The return value of i++ is the
> original value of i, before it was incremented.
ooohh! Of course!
Then it makes sense. (but the compiler should throw a warning, as it's
non-obvious code. For the 99% of the C# users who don't know the spec in every
detail)
FB
>
> -Chris
>
> -----Original Message-----
> From: Discussion of development on the .NET platform using any managed
> language [mailto:[email protected]] On Behalf Of Frans Bouma
> Sent: Tuesday, February 19, 2008 12:15 AM
> To: [email protected]
> Subject: Re: [DOTNET-CLR] Funny loop with post-increment.
>
> > Brady Kelly wrote:
> > > Why does this loop not exit? On the first iteration, one would expect i
> ==
> > > 0, and that 0 to be assigned to i, and then i incremented. Then, on the
> > > second iteration, i should be 1 before the assignment operation, as well
> as
> > > after the assignment operation, but i should be two after the
> > > post-increment, before the next assignment.
> > >
> > >
> > > int i = 0;
> > > while (i < 10)
> > > {
> > > i = i++;
> > > }
> >
> > i=i++ is effectively this:
> >
> > int tmp = i;
> > i = i + 1;
> > tmp = i;
> >
> > In other words, the increment happens after the evaluation of i, but
> > before the assignment - so the assignment just sets it back to the
> > original value.
>
> I don't find this obvious. Right-hand side of the assignment should
> be
> evaluated first, so:
> i=i+1
> i=i
>
> I don't see how /why a temp variable is suddenly created.
>
> FB
>
> ===================================
> This list is hosted by DevelopMentor. http://www.develop.com
>
> View archives and manage your subscription(s) at http://discuss.develop.com
===================================
This list is hosted by DevelopMentorĀ® http://www.develop.com
View archives and manage your subscription(s) at http://discuss.develop.com