Search code examples
cvisual-studio-2010variablesfor-loop

Error on Declaring variable in for statement


Is declaring a variable within for not allowed in C? Here is the code,

for(int i = 1; i<max; i++)

And I get error messages as,

error C2143: syntax error : missing ';' before 'type'
error C2065: 'i' : undeclared identifier

It works if I declare the variable i jut before the for loop,

int i;
for(i = 1; i<max; i++)

I was never expecting an error message on such a simple line of code. Can you please help me explain the reason behind this?

Edit:
I've Visual C++ 2010 Express. I'm using the command line compiler cl.

Update:
Based on replies, I've found Visual C++ 2010 doesn't support C98.

I've finally installed Visual Studio 2013 Express for Desktop which supports C98 and is working as expected.
Thanks to all of you for the valuable information.


Solution

  • Older MSVC versions support only c89 standard.

    pre-C99 standards, like c89 do not allow declaring variable in for-loop-params.

    Maybe use /TP option, which causes files to be compiled in C++ mode.