Infinite loops can be useful to execute some code until an exit signal is given. For example, a command line menu could be waiting forever until the user makes a valid choice. There are other approaches of course, but in case you need to know the syntax, here it is for all three loops.
Infinite for loop
1 2 3 4 |
// infinite for loop for (;;) { // repeat this forever } |
Infinite while loop
1 2 3 4 |
// infinite while loop while (TRUE) { // repeat forever } |
Infinite do-while loop
1 2 3 4 |
// infinite do-while loop do { // repeat forever } while (TRUE); |
To use the latter variations in C, replace the TRUE condition with 1.
How to exit from infinite loop?
Very good point Jayesh! You can exit loops at any time using the break statement. For example:
This works for finite loops as well of course.