Why is it bad practice to declare an int in a for loop?

Viewed 424

During my c++ courses at my university I got use to the practice of (and was taught to) declaring an int in a for loop like so:

for(int i = 0; i < 5; i++)
{
    // code
 }

But now that I’m in a mechatronics class where we write in c and Arduino the teacher told me it is bad practice to do this and suggested doing it this way:

int i = 0;
for(i; i < 5; i++)
    //code

Why would one be preferred over the other?

4 Answers

"mechatronics class"

I'm going to employ a reasonable guess.

The compiler you have is probably dumb and compiles this

for(int i = 0; i < 5; i++) {
    //code
}
for(int i = 0; i < 5; i++) {
    //code
}

to use two independent stack variables. Modern compilers are better than that but embedded systems have old dumb compilers, and old instructors remember the problems long after they're fixed. Given this is Arduino, if you've got an up-to-date compiler it's just plain old wrong now.

I remember using a compiler that would explode on this code with i has already been declared but I digress.

Why would one be preferred over the other?

In cases where you for example break out of the loop early, you might want to know the last value of i which is of course only accessible if it was declared outside the loop. So, in this case that is the only option (unless you use a separate variable for that, but this adds unnecessary complexity).

But generally when both are valid options, declaring all variables in smallest possible scope is potentially marginally more efficient, and easier to read - although latter may be subjective, so this is mostly a matter of taste. The former is objectively not "bad practice" in general.

To be honest, it's not bad practice, the only difference is the iterator will be accessible after the loop is finished running in the second scenario

The C89/ANSI standard requires all variables be declared at the top of a scope block. This was required because old C compilers were single pass compilers meaning they parsed, type checked, and emitted machine code during their one and only pass over the program. Since machine code is emitted as it's parsed, the amount of stack space to reserve for a given scope block needs to be known when it's encountered which is why old standards mandated that variables be declared at the top.

Newer C compilers are multi-pass compilers meaning they make multiple passes over the program. Because of this, it's no longer necessary to know how much stack space to reserve on the initial pass.

Embedded systems often use a C compiler adhering to the older C89/ANSI standard. Your teacher is likely encouraging you to declare variables at the top so you never have to think twice about it. They may give a more thorough explanation, as I have done, as the class progresses.

Related