How to compile a C project in C99 mode?

后端 未结 4 2052
隐瞒了意图╮
隐瞒了意图╮ 2020-12-14 17:03

I got the following error message while compiling the C code:

error: \'for\' loop initial declarations are only allowed in C99 mode
note: use option -std=c9         


        
4条回答
  •  一向
    一向 (楼主)
    2020-12-14 18:03

    You'll still need C99 if you want to mix statements and variable declarations. As other answers and the error message itself say, add -std=c99 to the command-line when you compile to enable C99 features [1].

    But you have always been allowed to write a compound statement (a "block", IOW, but the standard never uses this word!) in place of a single statement.

    #include
    int main() {
        int i = 5;
    
        {   /* new block, new declarations. */
            int i;
            for (i=0;i<10;i++){
            }
        }
        printf("%d\n", i);  /* prints "5\n" */
    }
    

    This is legal in K&R, C90 (aka C89, it's the same thing), and C99.

    Enabling C99 mode gets you lots of cool stuff, but it also disables some other cool stuff that gcc allows by default, like anonymous structures and unions within structures and unions.

    1. -std=gnu99 probably enables "all the goodies", but I caution you to avoid doing this. It will make unnecessary difficulty if you (or others) wish to port the code. I'd probably have a windows version of my pet project, ported for free by somebody, had I not done this very thing. It ties you gcc. You don't want to be tied. That's the whole bloody point of standards.

提交回复
热议问题