Question

I am using XC32 compiler by Microchip, and it does not allow declaration of variables inside loops (does not support C99), so I can not do this:

for(int i = 0;i<10;i++)
    {do w/e}

I would hate to make it a global, because it would be hard to keep track of it's value in big projects, using the same thing in various loops, even if you initialize it to i = 0 in every loop. I even had a bug with this, when it turned out to do weird stuff if you have a few nested loops using the same i.

As far as I understand, I can't "undeclare" it manually, but variables defined inside a block of code are undeclared after the pass trough the block? Is this true, and does that mean that this this code will act like the code above:

{
     int i;
     for(i = 0;i<10;i++)
        {do w/e}
}//no i anymore?
Was it helpful?

Solution

According to C99 standard, the scope of a variable declared in the clause statement of the for loop is restricted in scope to that loop.

In C89 / C90, that clause is merely an optional expression.

Therefore in C89 / C90 you can confidently emulate the C99 behaviour with

{ /*open scope block*/
   /* your declaration here, including possible definition*/
   for (expression; ...){
   }
} /*close scope block*/

OTHER TIPS

By putting it in a block you will indeed be rid of it at the conclusion of the block in question.

What this means exactly, however, depends on the compiler, the architecture, and the environment.

The variable scope is inside the block in which it is defined. So once the block is finished you cannot access the variable.

You may find this helpful:- Local variables display as “Out of Scope” when they are most clearly NOT out of scope.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top