C++ for loop with no conditions - c++

I ran across this
for ( ; ; ) {}
A quick cursory search lead me nowhere in finding out what this means. It looks like another thread might be handling terminating this. Is this equivalent to 'while (TRUE) {}' ?

This is an infinite loop. Any of the three parts of a for loop (initialization, condition and increment) can be missing. Specifically, if the condition in a for loop is missing, it is treated as being true. So it is equivalent to while(1) { ... }.

Yes they are equivalent in functionalities.

Related

C++ Single line If-Else within Loop

I read Why I don't need brackets for loop and if statement, but I don't have enough reputation points to reply with a follow-up question.
I know it's bad practice, but I have been challenged to minimise the lines of code I use.
Can you do this in any version of C++?
a_loop()
if ( condition ) statement else statement
i.e. does the if/else block count as one "statement"?
Similarly, does if/else if.../else count as one "statement"? Though doing so would become totally unreadable.
The post I mentioned above, only says things like:
a_loop()
if(condition_1) statement_a; // is allowed.
You can use ternary operator instead of if...else
while(true) return condition_1 ? a : b;
while seems redundant here if the value of its argument is always true so you can simply write
return condition_1 ? a : b;
Yes, syntactically you can do that.
if/else block is a selection-statement, which is a kind of statement.
N3337 6.4 Selection statements says:
selection-statement:
if ( condition ) statement
if ( condition ) statement else statement
switch ( condition ) statement

What's the difference between these two while loops?

What's the difference between these two while loops? I don't understand what they do.
First:
while(condition) ;
Second:
while(condition){ };
There's no difference, both while loops enclose an empty statement.
The practical result is an infinite loop which will never end, unless there's another thread or some side effect that changes condition.
first code is optional short form for second code, which is suitable when you need to do only 1 operation in loop, like:
while (condition is true)
condition=dosomething();
you can safely re-write this like:
while (condition is true)
{
condition=dosomething();
}
this will be absolutely the same
but if you need several statements in loop, you need to "group" them somehow, so compiler will know what parts of code should be "looped", this is done via { and }
so, for several statements you cannot use short form, you can only do:
while (condition is true)
{
condition=dosomething();
dosomething2();
dosomething3();
}
for multi-threading programming we can have next situation:
Thread1: set condition to true
Thread1: create new thread2 and run it
Thread1: now need to wait until thread2 is finished, thread2 will set condition to false when it done to notify 1st one
so, for such situations sometimes you can use infinite loop like
while (condition) ; or while (condition) { }; - which are the same as we see above
this mean - do single operation, but operation is not provided, this means just wait until other thread will set this variable to false
NOTE: such infinity loops usually is bad practice and it is better to avoid them and use only when you're sure that this has sense
The loops themselves are the same, but the second one is followed by the null statement, so if this code was oart of a larger control structure they could parse differently: for example, if they were part of a nested 'if' statement the first one could be followed by 'else', but the second could not.

Is there anything wrong with using an empty for loop?

It was a little while since I last programmed and I have seem to forgotten if it's acceptable to use an empty "for loop" for creating an infinite loop?
for(;;)
Currently I use this method in a program to make it repeatedly ask the user to enter two numeric values one for each double variable in the program. The programs then calls a function and calculates a sum of these two pairs of numbers.
To terminate the program i have "if" statements that check if the user input value is zero, If the value is zero the program terminates using an "Return 0;" argument.
The program checks each user input value if it's zero directly after the value has been assigned to the variable.
So to the real question: Is this a correct way to make my program do what i described? Or is there a more/better/accepted way of programming this?
And secondly is there anything wrong with use the "Return 0" argument the way i did in this program?
If you thinks it's hard to understand what I'll wrote or meant please reply, and I will take more time to write everything.
What you're doing is perfectly fine, and an idiomatic way of writing and exiting an infinite loop.
I always use while(true) for infinite loops
I've seen this in a few places:
#define forever for(;;)
forever {
}
Not sure I'd recommend it though.
for(;;) as well as while(1) both are acceptable. These are just conditional loops provided by the language and you can use them to have a infinite running loop as per your requirement.
This is valid, you can go ahead with your code.
Yes, it's totally acceptable. Once you have an exit condition (break or return) in a loop you can make the loop "infinite" in the loop statement - you just move the exit condition from the loop statement into the loop body. If that makes the program more readable you of course can do that.
For an infinte loop for (;;) is fairly common practice. But if you do have a condition, such a non-zero user input, you could always have that check done in a while loop.
You can also use while loop with condition to repeatedly request user to input.
while (condition) {
...
}
Instead of IF block to validation you can use the .
What you describe will work fine, but it is worth mentioning that certain strict coding standards (i.e. MISRA) would disapprove of using a return before the end of a function.
If your code is subject to such standards then you could use do-while loop with a suitable exit condition instead:
do {
// get userinput
if (userinput != '0')
{
// do stuff
}
} while (userinput != '0');

Are endless loops in bad form?

So I have some C++ code for back-tracking nodes in a BFS algorithm. It looks a little like this:
typedef std::map<int> MapType;
bool IsValuePresent(const MapType& myMap, int beginVal, int searchVal)
{
int current_val = beginVal;
while (true)
{
if (current_val == searchVal)
return true;
MapType::iterator it = myMap.find(current_val);
assert(current_val != myMap.end());
if (current_val == it->second) // end of the line
return false;
current_val = it->second;
}
}
However, the while (true) seems... suspicious to me. I know this code works, and logically I know it should work. However, I can't shake the feeling that there should be some condition in the while, but really the only possible one is to use a bool variable just to say if it's done. Should I stop worrying? Or is this really bad form.
EDIT: Thanks to all for noticing that there is a way to get around this. However, I would still like to know if there are other valid cases.
I believe that there are cases where it's fine for seemingly infinite loops to exist. However this does not appear to be one of them. It seems like you could just as easily write the code as follows
while (current_val != searchVal ) {
MapType::iterator it = myMap.find(current_val);
assert(current_val != myMap.end());
if (current_val == it->second) // end of the line
return false;
current_val = it->second
}
return true;
This seems to express the true intent of the loop better
My two cents is: code should be self-documenting. That is, when given a piece of code, I'd rather be able to look and tell the programmer's intent then have to read comments or trudge through the surrounding code. When I read:
while(true)
That tells me the programmer wanted an infinite loop; that the end condition couldn't be specified. This is the programmers intent in some circumstances; a server loop for instance, and that is when it should be used.
In the above code, the loop isn't meant to be forever, it has a clear end condition, and in order to be semantically clear, as others have pointed out:
while (currentVal != searchVal)
works, so the while(true) is clearly inferior and should be avoided in this instance.
There are times and places for infinite loops - I am not convinced this is one of them. On the other hand, it is far from being an egregious problem here.
while (currentVal != searchVal)
{
...
}
return true;
One place to use them is when the process is truly indefinite - a daemon process with a monitor loop that won't terminate.
There are situations where a construct like this makes sense:
The break condition is computed within the loop
There are more breaking conditions and they are all equally important
You really want an endless loop ;) ..
I agree with the other answers that there's no need for an infinite loop in this case.
However, another point might be that when you do have an infinite loop, for(;;) might be a better way to express it. Some compilers generate warnings for while(true) (condition always evaluates to false), and your intent is less clear because it looks like any other loop. Perhaps it used to say while (x == true), and you accidentally removed the x instead of the true. for(;;) says pretty clearly that this is intended to be an infinite loop. Or perhaps you intended to write something like while(t), but Intellisense in your IDE kicked in and decided to autocomplete to true.
for(;;) on the other hand, isn't something you'd ever type accidentally. (and it's easier to search for. while(true) could also be written as while(1))
Neither version is wrong, but for(;;) might be more intuitive because there is no loop condition.
while(true) is used in games for the main game loop - games continually read player input, process interactions between objects and paint your screen, then repeat. This loop continues infinitely until some other action breaks out of that loop (quitting the game, finishing the level).
I tried to quickly find this main loop in the Quake 1 source code for you, but there were at least 50 occurrences of 'while(1)', as well as some written as 'for(;;)', and I wasn't immediately sure which one was the main game loop.
Although I've done them before, I'd vote for always trying to go for the clearer solution by using something readable, which would generally include a valid expression in the while loop--otherwise you're scanning code to look for the break.
I'm not really terrified of them or anything, but I know some people are.
Well, a comment saying that it is not really an infinite loop would help:
while (true) // Not really an infinite loop! Guaranteed to return.
I do agree that it should have a condition, but this is okay in some situations (and it's not always possible or easy to make a condition).
Stop worrying. This is not bad form if it helps to simplify the logic of the code and improve maintainability and readability. Worthwhile though to document in comments on the expected exit conditions and on why the algorithm will not slip into an infinite loop.
Well, yes, but the two pages of code you have to write if you don't want your main loop to be something like while(true) is even worse form.
It is not uncommon to find infinite loops in embedded systems code - often surrounding finite state machines, checking peripheral chips and devices, etc.
I love infinite loops as the outside control structure of a finite state machine. It's effectively a structured goto:
for (;;) {
int c = ReadInput();
if (c == EOF)
return kEOF;
switch (state) {
case inNumber: state = HandleNumber(c); break;
case inToken: state = HandleToken(c); break;
case inWhiteSpace: state = HandleWhiteSpace(c);
default:
state = inError;
break;
}
if (state == inError) ThrowError();
}

Why use infinite loops?

Another poster asked about preferred syntax for infinite loops.
A follow-up question: Why do you use infinite loops in your code? I typically see a construct like this:
for (;;) {
int scoped_variable = getSomeValue();
if (scoped_variable == some_value) {
break;
}
}
Which lets you get around not being able to see the value of scoped_variable in the for or while clause. What are some other uses for "infinite" loops?
A loop like:
while (true)
{
// do something
if (something else) break;
// do more
}
lets you break out of the loop in the middle, rather than at the start (while/for) or end (do-while).
If you've got a complex condition, you might also want to use this style to make the code clearer.
I use an infinite loop for the body of my embedded control code, since it is designed to run forever once it is started.
while( 1 )
{
game->update();
game->render();
}
Edit: That is, my app is fundamentally based around an infinite loop, and I can't be bothered to refactor everything just to have the aesthetic purity of always terminating by falling off the end of main().
Finite state machines. They're not supposed to end until you reach an end state, at which point you break or return.
That's an incomplete example because it can be refactored to be an end-test loop with no loss of clarity, function or performance.
int scoped_variable;
do {
scoped_variable = getSomeValue();
} while (scoped_variable != some_value);
Infinite loops are most often used when the loop instance doesn't have the termination test at the top or the bottom, in the simplest case. This tends to happen when there is two parts to the loop: code that must execute each time, and code that must only execute between each iteration. This tends to happen in languages like C when doing things like reading from a file or processing a database resultset where a lot has to be done explicitly. Most languages with newer paradigms can structure such code actually into the test.
I would consider using an infinite loop to program the guidance system of a missile.
while ( true ) { go2Target ( ) ; }
From the perspective of the missile's guidance computer, the loop once started does repeat until the end of time.
Perhaps a purists would favor
while ( ! blown2Bits ( ) ) { go2Target ( ) ; }
but then how do you implement the blow2Bits method? what would it mean if blow2Bits returned true?
Nearly all apps use an infinite Main loop. ;)
One example is in a message pump type scenario, where you want to loop forever processing any messages that come in until told to stop. Another is if you want to take a periodic action then you might write an infinite loop with a sleep in it (though it may be better to use some form of timer for this).
There may be some other places where the loop has to perform a certain amount of work to determine whether it should exit, and it may be cleaner just to use break when this condition is true rather than set some external flag to indicate the loop should exit.
Generally though I think it's better practice to put your exit condition in the loop statement if possible, rather than to make it infinite and exit the loop using a break statement, because the exit condition of the loop is more obvious.
There are other questions relating to if/when it's ok to use break in a loop. Let's assume that we agree that it's sometimes ok. In those circumstances (hopefully rare) I would use an infinite loop if there are a number of terminating conditions and no identifiable "primary" terminating condition.
It avoids a long series of disjunctions (or's) and also draws the reader's attention to the fact that there may (almost certainly will) be breaks in the loop.
Ultimately it's a matter of taste.
I use them to write Linux daemons / services that loop until kill / other termination signals are received.
Infinite loops are useful mostly in daemon/service processes or the main loop in a game. You can even get cute with them, eg:
const bool heatDeathOfTheUniverse = false;
do
{
// stuff
} while(!heatDeathOfTheUniverse);
They should not be used to "wait" for things like threads as was suggested by Fry. You can use the Join method of a thread object for that.
However, if you're in a situation where your tech lead says, "infinite loops are verboten & so are multiple method/function returns & breaks" you can also do stuff like this:
bool done = false;
while(!done)
{
if(done = AreWeDone()) continue; // continue jumps back to start of the loop
}
Of course if you tech lead is forcing you to do such things you should start looking for a new job.
For more details on the continue keyword see this MSDN article.
Webservers use an infinite while loop:
while(true)
{
//Do something like respond to requests
}
They don't have to end unless you close your webserver application.
I used to use them when waiting for multiple threads to complete in c#, but now I use the ThreadPool class.
Other than embedded systems situations infinite loops always really are:
Repeat
Something
Until Exit_Condition;
But sometimes Exit_Condition isn't something that can actually be evaluated at the end of the loop. You could always set a flag, use that flag to skip the rest of the loop and then test it at the end but that means you are testing it at least twice (the code is slightly slower) and personally I find it less clear.
There are times when trading clarity for speed makes sense but something that gives neither clarity nor speed just to be technically correct? Sounds like a bad idea to me. Any competent programmer knows that while (true) means the termination condition is somewhere inside the loop.