Multiple Expressions in a for Condition

Every C programmer has screwed up a for loop’s statement. Having three arguments in one set of parentheses is just begging for trouble. That’s a lot of yard waste, but there’s a reason for all the detritus.

Before I dive into it, here’s how the for statement is described in my book, Beginning Programming with C For Dummies:

for(initialization; exit_condition; repeat_each)

Each item is separated by a semicolon. Occasionally I forget how it works ( 🙁 ) and I use a comma or colon. It happens.

Anything other than two semicolons in the statement raises the compiler’s eyebrows and the code, hopefully, doesn’t compile. But the code can compile if you add commas and take advantage of a neat for loop trick.

This code uses for to repeat a chunk of code 10 times, displaying values for variables x and y:

#include <stdio.h>

int main()
{
    int x,y;

    y = 0;
    for(x=0;x<10;x++)
    {
        printf("%2d:%2d\n",x,y);
        y+=2;
    }

    return(0);
}

Here’s the output:

 0: 0
 1: 2
 2: 4
 3: 6
 4: 8
 5:10
 6:12
 7:14
 8:16
 9:18

Cinchy.

The versatility of the for loop lets you do more than just play with the looping variable x inside its parentheses. You can also add an initialization and repeat_each statement to handle variable y. Consider this modification:

for(x=0,y=0;x<10;x++,y+=2)

Yes, the statement is quite cryptic and complex. The initialization part contains two expressions separated by a comma: x=0 and y=0. This double expression is legal in the C language.

The loop’s exit_condition remains unchanged.

The for loop’s repeat_each portion also has two expressions: x++ and y+=2, separated by using a comma.

With these modifications, the loop is reduced to a single statement:

#include <stdio.h>

int main()
{
    int x,y;

    for(x=0,y=0;x<10;x++,y+=2)
        printf("%2d:%2d\n",x,y);

    return(0);
}

The program’s output is the same.

Many C programmers delight in this type of cryptic statement. It saves lines of code and makes things look mysterious and cryptic, which they enjoy. I’ve used the comma a few times in my own code to shorten things up. It’s a nifty trick, but do be aware how it affects your code’s readability.

2 thoughts on “Multiple Expressions in a for Condition

Leave a Reply