Society of Robots - Robot Forum
Software => Software => Topic started by: jsmoker on November 21, 2007, 09:14:19 AM
-
I found this in some code I'm trying to use (in C++). Does anyone know what it means?
for( ; ; )
I know what a "for" does in cases like (int i = 0; i < 20; i++), but what's with the "( ; ; )".
-JSmoker
-
In C, a for loop looks like this:
for (index = 0; index < 10; index++)
That means to loop 10 times, with index incrementing from 0 - 9.
If you leave the three fields inside the parens blank, it basically means to loop forever...
- Jon
-
Well, it does look a little weird doesn't it? I've been programming for a while and have never seen it.
The common method of making an infinite loop is something like this:
while (true) {
//Code and so on...
Basically it means the expressions are empty, so that means they result in true (which makes the for loop infinitely), right?
-
ok, I got it, the author was just using it as a variation of a while loop:
instead of:
int x = 1;
while(x)
{
if(case)
x= 0;
}
he did:
int x = 1;
for( ; ; )
{
if(case)
break;
}
-
Yeah, the reason you didn't recognize that straight off is because no recently created programming language allows for it. Thank goodness.
http://www.xkcd.com/292/
-
are there any advantages to it? such as is it easier to break out of without taking up a variable?
-
That method of coding is a nightmare to any experienced coder. Even a "while(true);" makes SOME (not all) programmers cringe. In my experience, readings, and observation ive found that the best thing to do is to create a simple global integer or boolean and set it to 'true' or '1' and have a while loop have that variable as its condition. Offers more control and is a little more stable... That might just be paranoia and this programming book I recently read talking :P
-
That method of coding is a nightmare to any experienced coder. Even a "while(true);" makes SOME (not all) programmers cringe. In my experience, readings, and observation ive found that the best thing to do is to create a simple global integer or boolean and set it to 'true' or '1' and have a while loop have that variable as its condition. Offers more control and is a little more stable... That might just be paranoia and this programming book I recently read talking :P
Yeah, i agree with that. I often use a boolean variable called quit, and set it false and have the loop look like this: "while(!quit)". Whenever i need to jump out of that loop i just set quit to true. Thats feels like a pretty neat solution for me. Design is pretty important in programming, especially if you are studying programming and the teacher need to see how the program works...