Jesse
Jesse

Reputation: 55

Undeclared variable in C while it has been declared

I created a for-loop in C, which should work, Eclipse however told me that I used an undeclared variable, here's my code:

#include <stdio.h>

int main( int argc, char ** argv ) {
for(int i = 1; i <= 5; ++i) {
    printf("i is %d\n", i);
}
return 0;
}

according to Eclipse the undeclared variable, is i on the printf line it has been declared in the for statement right? This code is the exact same code as used in the tutorial I am following, it did work in the video though.

Upvotes: 1

Views: 545

Answers (1)

TheMP
TheMP

Reputation: 8427

In ANSI C (unlike C90/C11) you cannot declare variables in for loop. You unfortunatelly have to to this (or change your compiler to a more modern one, you won't be compatible with the ANSI standard though):

int main( int argc, char ** argv ) {
int i;
for(i = 1; i <= 5; ++i) {
    printf("i is %d\n", i);
}
return 0;
}

Upvotes: 3

Related Questions