To Increment Before or After

Say you have a for loop that increments one notch each time it repeats. I code such a loop in this fashion:

for(x=0;x<10;x++)

More common, however, programmers use this approach:

for(x=0;x<10;++x)

The difference is in how the variable x is incremented. I put the ++ after the x, but most coders put it before. What the deal?

Whether you specify x++ or ++x is merely a matter of preference. That's because the value of x isn't being assigned to something. In the for loop's guts, the x++ or ++x is its own statement.

In their seminal work, The C Programming Language, Brian Kernighan and Dennis Ritchie use ++x in their for loop examples. I read that book when I was first learning C, as well as multiple other books. I can only assume that the last book I read — the one where C finally clicked for me — showed x++ in a for loop. That's my best guess.

Whether you use one approach or the other, the value of variable x is incremented the same as the for loop spins. Here's sample code for my method:

#include <stdio.h>

int main()
{
    int x;

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

    return(0);
}

I ran this code to check the value of variable x inside the loop and when the loop is done. Here's the output:

0
1
2
3
4
5
6
7
8
9
10

If I modify Line 7 to read for(x=0;x<10;x++), the output is the same: The loop starts with x equal to 0 and ends with x equal to 9. After the loop is done, in both cases, x equals 10.

Consider this issue one of preference only. It matters not whether x is incremented before or after, the results are the same.

In a way, this choice is similar to how I write my return statements. I use parentheses but a lot of C coders choose not to. The parentheses optional when return specifies a single value, so using one or the other is simply a matter of preference.

Leave a Reply