error: ‘for’ loop initial declarations are only allowed in C99 mode 处理方法

在Ubuntu中用gcc编译如下程序时遇到了如题所示的错误

#include<stdio.h>
int main(int argc,char **argv)
{
    int sum=0;
    for (int i = 0; i <= 10; i++)
    {
        sum+=i;
    }
    printf("sum is %d\n",sum);
    return 0;
}
 
产生错误的主要原因是gcc所支持的是c89版本,而在for循环中进行定义变量是c99支持的。
所以可将编译指令由
gcc for.c -o for.out
改为
gcc -std=c99 for.c -o for.out
即可。

猜你喜欢

转载自www.cnblogs.com/elecyang/p/12657091.html