Loop variable declaration error

Asked

Viewed 633 times

4

I made the following command:

for(int i = 1 ; i <= 3 ; i++) {etc
}

Then it made the following mistake when I went to compile:

game.c:11:2: error: "for" loop initial declarations are only allowed in C99 mode
for(int i = 1 ; i <= 3 ; i++) {
/\ //essa seta apontando pro "f"
game.c:11:2: note: use option -std=c99 or -std=gnu99 to compile your code

What to do?

  • 1

    As the error message itself said, use the option -std=c99 or -std=gnu99 when calling the compiler (or moving the int i out of the loop). Apparently you cannot declare a variable inside a for in the version of C you are using (this can from C99).

  • For reference, the difference between using c99 and gnu99 is that this second allows GNU extensions (i.e. gcc-specific), while the first follows more strictly the specification. So if you want code portable (which can be compiled by other types of C compiler), use the first, if you want/need some specific extension, use the second.

3 answers

7

In the version of C you are using it is not allowed to create a variable within a command for

Try separating the instructions in:

int i;
for (i = 1; i <= 3; i++){ etc... }

6

Must do what the message is saying, put -std=c99 command line when compiling.

If you can’t interpret a simple error message that tells you what to do, you’ll have enormous difficulties programming, it happens all the time. Especially in C, you have some pretty hairy mistakes. So pay attention to what the compiler tells you, he may not be able to solve for you, but he says important things. In simple things like this just follow what he says in the error message.

Or you can do what the other answers say but this is an archaic technique that should be avoided if there is no reason to use it.

  • I started today, I’m still picking up... = D

  • The best tip I’m giving you is to pay close attention to what the compiler tells you, he knows what’s wrong and gives you important and correct information about what to do. Of course some can be interpreted, but this is very simple.

  • beauty, I’ll dedicate more!

5

Put the whole declaration out of the loop:

int i;
for(i = 1 ; i <= 3 ; i++) { ... }

Possibly this compiler version is quite old, or is defined for version C89.

Another solution you can try to do is to compile it as follows:

$ gcc -g game.c -std=c99

Or else:

$ gcc -g game.c -std=gnu99

Browser other questions tagged

You are not signed in. Login or sign up in order to post.