FriskySaga
FriskySaga

Reputation: 439

Which is the better way to declare dummy variables for nested loops?

  1. The advantage of approach 1 is a slightly smaller file size due to less text characters in the source code:

    int i, j;
    for (i = 0; i < numRows; i++)
        for (j = 0; j < numCols; j++)
        //<some code here>
    
  2. The advantage of approach 2 is the smaller scope of local variables.

    int i;
    for (i = 0; i < numRows; i++)
    {
        int j;
        for (j = 0; j < numCols; j++)
        //<some code here>
    }
    

Even if the differences in optimizations are negligible in today's modern computers, which approach is considered "better" code?


Edit to clarify that this question is not a duplicate:

This question is based on the current C11 standard, which does not allow for syntax like this:

for (int i = 0; i < numRows; i++)

In C++ and C99, this syntax is perfectly acceptable whereas C11 does not allow for variable declarations inside the for statement.


Edit to correct misinformation:

I thought I was using C11 because I had recently downloaded the compiler from CodeBlocks, so that's why I said C11 didn't allow for variable declarations inside the for statement. But it turns out I was actually using C90, which was the root of my problems.

Upvotes: 2

Views: 1246

Answers (4)

Peter
Peter

Reputation: 36597

Neither approach is preferred.

Two common coding guidelines are (1) to ensure that no variable exists any longer than it needs to and (2) don't use a variable for more than one thing. Following such guidelines reduces (often, but not always, eliminates) accidental usage of a variable in a way that is not intended, and therefore helps avoid subtle programming errors.

In your first case, both i and j continue to exist until the end of the enclosing scope - which means they exist after the loops are complete. This maximises the chances of subsequent code (in that enclosing scope) accidentally reusing i or j for another purpose (e.g. when the intent is to use another variable). Such bugs are often hard to find.

The second case has the same problem, except with i only. Even one variable with such a problem is bad news though.

I'd probably use a construct like

// unintentionally using i or j here will cause a compilation error

for (int i = 0; i < numRows; i++)
{
    // unintentionally using j here will cause a compilation error

    for (int j = 0; j < numCols; j++)
    {
       //<some code here>
    }

    // unintentionally using j here will cause a compilation error
}

// unintentionally using i or j here will cause a compilation error

(The comments I've inserted to make the point make this more unreadable, but such comments will not normally be needed in practice).

This ensures that neither i not j exist outside the outer loop. It also means that j cannot be accidentally used in the outer loop. Practically, it is easy to type i when j is intended (and vice versa) - for example, they are close together on a QWERTY keyboard. i and j also look quite similar visually, so visual code inspections often miss such errors. However, using an approach like this, the COMPILER will detect such typos. Given a choice, it is better to have a compiler pick up errors rather than for a human to have trouble finding them.

Of course, this doesn't prevent misuse or interchange of i and j in the inner loop - but that's one reason that guidelines often encourage use of more informative names than i and j - misuse of visually different names is easier for a mere mortal to detect.

Upvotes: 1

A. P. Damien
A. P. Damien

Reputation: 386

This seems be a question of taste rather than having any definite answers, but I'll give you my opinion:

Given current computers, saving a couple of characters of source code is too trivial to even think about. In fact, I think I would have said that even when I was learning C on a VAX 11/780 in 1976.

I would favor the second example, because the current preference is to declare variable as close to the first use as possible. In C++ you could even put the declarations of the loop variables inside the for statements:

for (int i = 0; i < numRows; i++) {
   for (int j = 0; j < numCols; j++) {
      ...
   }
}

But that's still just a matter of taste: the belief that the program will be more readable if the declaration of a variable is close to its use.

Upvotes: 1

ad absurdum
ad absurdum

Reputation: 21317

For sheer compactness and limiting of scope, I would use:

for (size_t i = 0; i < numRows; i++) {
    for (size_t j = 0; j < numCols; j++) {
    //<some code here>
    }
}

Note the use of size_t for what appear to be array indices. The size_t type is an unsigned integer type guaranteed to be able to hold any array index. Just a matter of style, but I would also suggest using braces around all loop bodies. This makes it much less likely that you will break your code with inevitable updates and changes.

By making it a habit to declare loop variables with block scope like this, you force yourself to choose to use the values stored in loop variables elsewhere in your code.

Upvotes: 5

ashokrajkp
ashokrajkp

Reputation: 19

The second method is the best method as

  1. It can use low memory
  2. Allows usage of same variable again if required in any other loop

Upvotes: -1

Related Questions