In C89 all variables should be declared at the top of a code block i.e. directly after a {
, they don't have to be declared at the top of a function. In C99 and later they can be declared anywhere. If you have a section of code in your function that needs to use a set of variables that the rest of the function doesn't you can wrap this section in a block {...
}`.
C - While loop before variables not compiling [duplicate]
-
17-07-2023 - |
Domanda
I'm trying to make a loop in the main method in C, and it's not compiling.
Here's the code:
int i = 1;
while (i < 10)
{
i++;
}
int x;
int a;
int b;
int sum;
sum = a + b;
It doesn't compile because this error:
Error 3 error C2143: syntax error : missing ';' before 'type'
This error appears in all the variables that are declared after the loop.
But, if I write the loop after these variable declaration, it works just fine.
So why can't I write a loop before variable declaration?
Soluzione
Altri suggerimenti
This is the typical response of an outdated Microsoft Visual C compiler which does not support the latest C standard. Seems they've got stuck in time.
Just move the variables before the loop and all should be fine.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow