Abdullah Leghari
Abdullah Leghari

Reputation: 2470

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.

Upvotes: 1

Views: 1751

Answers (5)

BLUEPIXY
BLUEPIXY

Reputation: 40145

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.

Upvotes: 3

Lundin
Lundin

Reputation: 213693

Visual Studio is very poor when it comes to C and only supports a 24 years old, obsolete version of C called C90. And it supports that version poorly. Microsoft has no strictly conforming C compiler.

If you use a real C compiler instead, the code will compile just fine.

Upvotes: 0

cytoscope
cytoscope

Reputation: 129

You are probably using pre-C99 standard compiler. In C89/ANSI C you have to declare variables in the beginning of the scope block. Pay attention to that because you will most likely get similar errors from declaring variables after you have made some function calls etc.

Upvotes: 3

unwind
unwind

Reputation: 399793

It's C99, and your compiler is probably too old or not set correctly to use this "new" standard.

Upvotes: 0

Nikola Smiljanić
Nikola Smiljanić

Reputation: 26873

It's only allowed in C99. Not sure what compiler you're using, clang and gcc have std=c99.

Upvotes: 1

Related Questions