Simple do while loop using while(true);

Dev picture Dev · Feb 18, 2013 · Viewed 46.7k times · Source

Many times in the examples of C programs, I came across these kind of loops. What do these kind of loops really do?

do {

    while (...) // Check some condition if it is true.
    { 
        calculation 1
    }

    // Some new condition is checked.

} while(true);

What is the need of while(true); Is it used for infinite looping? Can someone please explain what the above loop really does. I am new to C programming

Answer

Sargam Modak picture Sargam Modak · May 25, 2015

These loops are used when one wants to loop forever and the breaking out condition from loop is not known. Certiain conditions are set inside the loop along with either break or return statements to come out of the loop. For example:

while(true){
    //run this code
    if(condition satisfies)
        break;    //return;
}

These loops are just like any other while loop with condition to stop the loop is in the body of the while loop otherwise it will run forever (which is never the intention of a part of the code until required so). It depends upon the logic of the programmer only what he/she wants to do.