CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Some unusual loops you will encounter

As you read more C programs written by others, you'll see some statements that look like for or while loops, but appear to have something missing.
In fact, any (or all!) of the 3 "parts" of a for loop may be omitted.

For example, the following loop initially sets i to 1, and increments it each iteration, but it doesn't have a "middle" conditional test to see if the loop has finished. The missing condition constantly evaluates to true:

for(int i = 1 ; /* condition is missing */ ; i = i+1) {
    .....
    .....
}

Some loops don't even have a loop-control variable, and don't test for their termination. This loop will run forever, until we interrupt or terminate the operating system process running the C program.
We term these infinite loops :



// cryptic - avoid this mechanism
for( ; ; ) {
    .....
    .....
}


#include <stdbool.h>

// clearer - use this mechanism
while( true ) {
    .....
    .....
}

While we often see and write such loops, we don't usually want them to run forever!

We will typically use an enclosed condition and a break statement to terminate the loop, either based on some user input, or the state of some calculation.

 


CITS2002 Systems Programming, Lecture 2, p17, 25th July 2023.