error: ‘for’ loop initial declarations are only allowed in C99 mode [duplicate]

独自空忆成欢 提交于 2021-02-06 07:29:39

问题


I am getting the below error, what is std=c99/std=gnu99 mode?

source Code:

#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`

回答1:


This happens because declaring variables inside a for loop wasn't valid C until C99(which is the standard of C published in 1999), you can either declare your counter outside the for as pointed out by others or use the -std=c99 flag to tell the compiler explicitly that you're using this standard and it should interpret it as such.




回答2:


You need to declare the variable j used for the first for loop before the loop.

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



回答3:


Easiest Solution by "Prof. Dr. Michael Helbig" . it will switch your mode to c99 so you don't have to add flag every time in make file http://www.bigdev.de/2014/10/eclipse-cc-for-loop-initial.html?showComment=1447925473870#c6845437481920903532

Solution: use the option -std=c99 for your compiler! Go to: Project > Properties > C/C++ Buils > Settings > Tool Settings > GCC C Compiler > Dialect > Language Standard: choose "ISO C99"




回答4:


This will be working code

#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;
    }


来源:https://stackoverflow.com/questions/29338206/error-for-loop-initial-declarations-are-only-allowed-in-c99-mode

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!