Reputation: 823
When trying to compile simple c++ project, I get the following error:
syntax error : missing ';' before '{'
I did my research. Compiler doesn't allow declaration of variables inside of a for loop, which is very inconvenient for me. If I declare loop variables before the for loop, the error disappears.
This is a c++ project with "stdafx.h" precompiled header.
Is this compiler behavior (C89) enforced by the fact that I'm using precompiled header or did I scr**ed something up with my config in the past ? Is there any way of circumventing this befavior ?
P.S. I'm using visual studio 2012 on windows 7 64-bit;
Code samples:
error is on the first line
for (int idx = 0, int i = 100; idx < (sizeof(anTestScores) / sizeof(int)); i++, idx++)
{
anTestScores[idx] = i;
}
this compiles
int idx;
int i;
for (idx = 0, i = 100; idx < (sizeof(anTestScores) / sizeof(int)); i++, idx++)
{
anTestScores[idx] = i;
}
Upvotes: 0
Views: 825
Reputation: 5856
Go with
for (int idx = 0, i = 100; idx < (sizeof(anTestScores) / sizeof(int)); i++, idx++) { anTestScores[idx] = i; }
This declares two variables of type int in the first statement of the for
loop.
The reason this works and your other attempt doesn't is as follows:
Each declaration statement has to be separated from each other by a ;
, but the same ;
is used to separate parts of the for(;;)
loop's header so you tried to get around it by using the ',' operator. Which didn't work due to syntax error
Upvotes: 7