How to create infinite loops in Objective-C and C

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

// infinite for loop
for (;;) {
    // repeat this forever
}

Infinite while loop

// infinite while loop
while (TRUE) {
    // repeat forever
}

Infinite do-while loop

// infinite do-while loop
do {
    // repeat forever
} while (TRUE);

To use the latter variations in C, replace the TRUE condition with 1.





2 thoughts on “How to create infinite loops in Objective-C and C

    1. Very good point Jayesh! You can exit loops at any time using the break statement. For example:

      for ( ; ; ) {
          if (i == 47) {
              break;
          }
      }
      

      This works for finite loops as well of course.

Leave a Reply