Question:
Why won't my (beginner) C code compile?
lgore93
2012-07-26 08:52:05 UTC
I will be going to college in the fall for computer science, and I'm trying to get a head start on things. I already know Java, but now I'm trying to learn C.

My code:
#include

int main()
{
int number = 0;
printf("%d\n", number);
for (int i = 0; i < 25; i++)
{
printf("%d\n",i);
}
return 0;
}

I'm running this in Visual C++ Express, and it's going crazy over me declaring and initializing "i" in the for variable all at once. Am I maybe leaving something out? In Java, this is the standard way to create a for loop.

I thought that maybe since I'm using the Visual C++ compiler, it was somehow not compiling correctly. If I declare i from outside the loop, everything works fine. I made the first line (int number = 0) to make sure that variables can be initialized as they're declared. This has me stumped.

Note: Yes, I'm using the C compiler of Visual C++, so this can't be the problem.
Error list from build attempt:
1>hey.c(7): error C2143: syntax error : missing ';' before 'type'
1>hey.c(7): error C2143: syntax error : missing ';' before 'type'
1>hey.c(7): error C2143: syntax error : missing ')' before 'type'
1>hey.c(7): error C2143: syntax error : missing ';' before 'type'
1>hey.c(7): error C2065: 'i' : undeclared identifier
1>hey.c(7): warning C4552: '<' : operator has no effect; expected operator with side-effect
1>hey.c(7): error C2065: 'i' : undeclared identifier
1>hey.c(7): error C2059: syntax error : ')'
1>hey.c(8): error C2143: syntax error : missing ';' before '{'
1>hey.c(9): error C2065: 'i' : undeclared identifier
Four answers:
justme
2012-07-26 08:58:26 UTC
In C, variables must be defined at the beginning of the function. So for (int i ... is illegal
koppe74
2012-07-26 16:03:43 UTC
Declaring an index-variable inside a loop like that is C++ syntax. In C you must (or at least should) declare all variables - including loop-indeces like this - in the beginning of the block.



So try:



#include



int main()

{

int i, number = 0; /* Here I also declare the loop-index i */

printf("%d\n", number);

for (i = 0; i < 25; i++) /* Here I set i to 0 */

{

printf("%d\n",i);

}

return 0;

}
adaviel
2012-07-26 15:56:19 UTC
In gcc on Linux I get:

try.c:7: error: ‘for’ loop initial declarations are only allowed in C99 mode

try.c:7: note: use option -std=c99 or -std=gnu99 to compile your code



If I declare int i outside the loop, it works fine.
anonymous
2012-07-26 15:58:33 UTC
I remember reading that Microsoft's Visual C compiler only supports C89. for loop declarations were introduced in C99, so you'll need to get a better compiler like GCC or Clang if you want to compile code like this.



edit: http://en.wikipedia.org/wiki/C99#Implementations


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...