for문 변수 선언 오류

Dev C++에서 작성한 아래 코드에서 오류가 발생했다.

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

 

[Error] 'for' loop initial declarations are only allowed in C99 or C11 mode
[Note] use option -std=c99, -std=gnu99, -std=c11 or -std=gnu11 to compile your code

 

또는 아래와 같은 오류를 출력한다.

'for' loop initial declaration used outside C99 mode

 

이는 for문 내에서 반복자인 i를 선언해서 발생한 문제다. ANSI C에서는 for문 내에서 반복자를 선언할 수 없기 때문에 C99 이상을 사용하거나 for문 밖에서 반복자를 선언해야 한다.

 

방법1 : for문 밖에서 반복자 선언

int main()
{
	int i; // 선언
	for(i=0; i<10; i++)
	{
		printf("%d\n", i<<16);
	}
}

 

 

방법2 : C99 이상 사용

상단 Tools에서 Compiler Options을 선택한다.

 

 

 

 

Compiler Options에서 Add the following commands when calling the compiler를 체크하고 -std=c99를 입력한다.

C99 이외에도 다른 버전을 입력할 수도 있다. ex) -std=c11