| View previous topic :: View next topic |
| Author |
Message |
Arne Schmitz Guest
|
Posted: Wed Dec 14, 2005 3:44 pm Post subject: Changing the variable of a for loop |
|
|
Does the changing of an iterator variable in a for loop result in undefined
behaviour? For example
for (int i = 0; i < 5; ++i)
i = 6;
Arne
--
[--- PGP key FD05BED7 --- http://www.root42.de/ ---]
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
Jeffrey Schwab Guest
|
Posted: Wed Dec 14, 2005 7:26 pm Post subject: Re: Changing the variable of a for loop |
|
|
Arne Schmitz wrote:
| Quote: | Does the changing of an iterator variable in a for loop result in undefined
behaviour? For example
for (int i = 0; i < 5; ++i)
i = 6;
|
No, but you probably should comment that.
i = 6; // Loop will end on next test.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
vord.fok@gmail.com Guest
|
Posted: Wed Dec 14, 2005 7:27 pm Post subject: Re: Changing the variable of a for loop |
|
|
Undefined behaviour .. mm lets see .
You type in i=6 in the instruction .
the cycle is over and the he reads his for again . the statement says i
< 5 . the answer is i is bigger then 5 and he exit the loop . no
problem .
Why should that give any problems ?
your using this in coalition with an if statement or else there would
be no reason to make that loop in the first place .
that is a good solution if you want to go trough the loop without using
a break .
Greetings
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
Thomas Tutone Guest
|
Posted: Wed Dec 14, 2005 7:27 pm Post subject: Re: Changing the variable of a for loop |
|
|
Arne Schmitz wrote:
| Quote: | Does the changing of an iterator variable in a for loop result in undefined
behaviour? For example
for (int i = 0; i < 5; ++i)
i = 6;
|
No, you are free to change that variable in the loop, and the behavior
is well defined. What you've written is equivalent to (leaving aside
variable scope issues):
{
int i = 0;
while (i < 5) {
i = 6;
++i;
}
}
Best regards,
Tom
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
|