cvariablesfor-loopcompiler-errorstexas-instruments

Declaring a variable inside a for loop; getting error with c2000 compiler


I am working on a C project for a TI TMS320x DSP with the C2000 compiler. I tried to initialized a loop variable directly inside a for loop, but somehow I get a compiler error:

Code:

for (int TabCnt = 0; TabCnt < 10; TabCnt++)
{
    x++;
}

Error:

error #20: identifier "TabCnt" is undefined

I figure this might be a wrong compiler setting? If I declare the variable outside of the loop, it works perfectly.


Solution

  • That's because you are using a compiler that supports only C89.

    This syntax:

    for (int TabCnt = 0; TabCnt < 10; TabCnt++)
    

    is only valid since C99. The solution is either enable C99 if supported, or declare variables in the beginning of a block, e.g:

    void foo()
    {
        int x = 0;
        int TabCnt;
        for (TabCnt = 0; TabCnt < 10; TabCnt++)
        {
            x++;
        }
    }