A Review of for Loops


RSS
Follow by Email
Facebook
Facebook
Google+
Google+
http://beningo.com/151-a-review-of-for-loops/
YouTube
LinkedIn

Conditional loops are common in every programming language whether it’s designed for low level embedded development or higher level web or pc development. The most commonly used loop is the well known for loop. When writing a for loop in C, there are multiple perturbations or uses that exhibit what could be considered unexpected behavior.

 

The for loop is defined as follows:

 

for( [expression1] ; [expression2]; [expression3] )

 

expression1 – is an initialization and only executed once before the first loop begins
expression2 – is the control expression. It is tested before executing the loop and ceases when this expression is evaluated as false.
expression3 – is the adjustment expression. It is performed after each loop but before expression2 is evaluated.

 

The most common example of the for loop looks something like this:

 

for(int i = 0; i < Count; i++)
{
// Do something
}

 

The loop is evaluated Count times before moving on to the next piece of code. There are two additional less commonly used forms of the for loop. The first is to create an infinite loop and looks like the following:

 

for(;;)
{
// Do something forever
}

 

In this case since expression2 does not exist, it is by default always evaluated as being true. There is another special case where the for loop can be made to behave like a while loop. A while loop will execute until an expression is true. Declaring a for loop as follows has the exact same effect:

 

for(;Flag == TRUE;)
{
// Loop while Flag is TRUE
}

 

This is the same as writing

 

while(Flag == TRUE)
{
// Loop while Flag is TRUE
}

 

The interesting fact is that while we are used to seeing the common usage of for, any of the three expression terms can be omitted! A fact that is often commonly forgotten (and possibly not terribly useful but still interesting).

RSS
Follow by Email
Facebook
Facebook
Google+
Google+
http://beningo.com/151-a-review-of-for-loops/
YouTube
LinkedIn

Comments are closed.