Old Habits Die Hard

Like doing anything for a long period of time, I find myself often using the same approach to solving a programming puzzle. It’s habit. It’s tradition. And it often hinders my insight into the language.

As an example, when I write code that works through a string, I always use a while loop. Always. I suppose that’s the way I learned how to manipulate a string one character at a time. To wit:

#include <stdio.h>

int main()
{
    char string[] = "Of all the gin joints in the world...\n";
    int x;

    x = 0;
    while( string[x] )
    {
        putchar( string[x] );
        x++;
    }

    return(0);
}

The while loop keeps spinning until the value of string[x] is false, which means it returns the null character in this example. The three parts of the while loop are split between three lines:

  • Initialization of variable x at Line 8
  • The exit condition specified at Line 9.
  • The loop stepping value at Line 12.

This code represents my traditional approach, but it’s not the only way to process a string one character at a time.

In the code below, I use a for loop to process a string. I’ve never used a for loop in this manner; normally I use a for loop as a counter, but yet it can work through characters just like a while loop:

#include <stdio.h>

int main()
{
    char string[] = "Of all the gin joints in the world...\n";
    int x;

    for( x=0; string[x]; x++)
    {
        putchar( string[x] );
    }

    return(0);
}

Unlike the preceding example, in the code above all the loop elements appear in one place, within the for loop’s parentheses at Line 8. In fact, the loop can be tightened further:

#include <stdio.h>

int main()
{
    char string[] = "Of all the gin joints in the world...\n";
    int x;

    for( x=0; putchar(string[x]) ; x++)
        ;

    return(0);
}

The putchar() function returns the value of the character output, which means the null character can still stop the loop. The sole semicolon on Line 9 signals to the compiler that I’m aware the loop has no statements and did not unintentionally create an endless loop.

Now that I recognize I’m stuck in a rut with my approach to processing strings, I’m curious see what other habits I have that can be broken. I must plow through my code to see whether my approach to solving a problem is done from tradition. Certainly other methods must be available. If I desire to boost my programming kung fu, it helps to be aware of such peccadilloes.

Leave a Reply