【问题标题】:error: ‘for’ loop initial declarations are only allowed in C99 mode [duplicate]错误:“for”循环初始声明仅在 C99 模式下允许 [重复]
【发布时间】:2015-06-02 23:54:18
【问题描述】:

我收到以下错误,什么是 std=c99/std=gnu99 模式?

源代码:

#include <stdio.h>

void funct(int[5]);

int main() 
{        
    int Arr[5]={1,2,3,4,5};
    funct(Arr);
    for(int j=0;j<5;j++)
    printf("%d",Arr[j]);
}

void funct(int p[5]) {
        int i,j;
        for(i=6,j=0;i<11;i++,j++)
            p[j]=i;
}


Error Message:
hello.c: In function ‘main’:
hello.c:11:2: error: ‘for’ loop initial declarations are only allowed in C99 mode
for(int j=0;j<5;j++)
      ^
hello.c:11:2: note: use option -std=c99 or -std=gnu99 to compile your code`

【问题讨论】:

  • 您需要在 for 循环之外声明 j,或者使用 -std=c99 选项(如错误消息状态)进行编译。

标签: c loops


【解决方案1】:

发生这种情况是因为在 for 循环中声明变量直到 C99(这是 1999 年发布的 C 标准)才有效 C,您可以按照其他人指出的那样在 for 之外声明计数器或使用 -std =c99 标志明确地告诉编译器你正在使用这个标准,它应该这样解释它。

【讨论】:

  • 非常感谢亚历杭德罗。能否请您告诉我如何在 linux 编译中使用 -std=c99 标志??
  • @Rajitsrajan 只需将-std=c99 添加到您的命令行即gcc main.c -o main -std=c99
【解决方案2】:

你需要在循环之前声明用于第一个for循环的变量j。

    int j;
    for(j=0;j<5;j++)
    printf("%d",Arr[j]);

【讨论】:

    【解决方案3】:

    “Michael Helbig 教授”最简单的解决方案。它会将您的模式切换到 c99,因此您不必每次都在 make 文件中添加标志 http://www.bigdev.de/2014/10/eclipse-cc-for-loop-initial.html?showComment=1447925473870#c6845437481920903532

    解决方案:为您的编译器使用选项 -std=c99!转到:项目 > 属性 > C/C++ 构建 > 设置 > 工具设置 > GCC C 编译器 > 方言 > 语言标准:选择“ISO C99”

    【讨论】:

      【解决方案4】:

      这将是工作代码

      #include <stdio.h>
      
          void funct(int[5]);
          int main()
          {
               int Arr[5]={1,2,3,4,5};
               int j = 0;
      
              funct(Arr);
      
              for(j=0;j<5;j++)
              printf("%d",Arr[j]);
          }
          void funct(int p[5]){
              int i,j;
              for(i=6,j=0;i<11;i++,j++)
                  p[j]=i;
          }
      

      【讨论】:

      • 对 OP 的解释会有所帮助。
      猜你喜欢
      • 2017-10-28
      • 1970-01-01
      • 2011-08-18
      • 2013-01-19
      • 2015-07-21
      • 2021-03-29
      • 2010-09-06
      相关资源
      最近更新 更多