On-the-fly Variables

Traditionally, a C program announces its variables at the start of a function block. The variables are presented by type and name, and they can be initialized at that time as well. This tradition isn’t a rule, and many C programmers break it.

I’m not one of those programmers. Being a traditionalist, and also desiring some consistency, I keep variable declarations at the start of my code. My reasons are the same as my motivation for keeping my car keys in the same spot in my house; I can always find them — providing that I habitually keep them at that location. (That process occasionally has flaws, but you get my point.)

One place I’ve seen variables declared in a non-traditional manner is in a for loop. The counting variable, which is usually a throw-away integer, is declared right in the for statement. Inhale the following code:

#include <stdio.h>

int main()
{
    for(int x = 0;x<10;x++)
        printf("Counting: %d\n",x+1);

    return(0);
}

Variable x is declared right at the start of the for statement: int x = 0. I see this technique used often, and it’s okay: The code compiles and runs just as if you declared x on a line by itself.

In fact, even if you used the identical technique in another for loop elsewhere in the code, the compiler won’t balk. That’s a credit to habit, but I’m still more comfortable declaring all the code’s variables in one batch.

Yes, my insistence upon tradition means that you must be flexible with your text editor. Many times I’ve been deep in the bowels of some 500-line monster code and suddenly needed a new variable. So I fly up to the top of the block and write the variable’s definition, then fly back. I’m okay with that process.

And remember that you can’t use a variable before it’s declared. C programs read top-down, so the variable must be declared “above” wherever it appears in the code.

Leave a Reply