ISO C90 forbids mixed declarations and code becaus

2019-08-13 18:38发布

I tried compiling it using -gcc and it worked as intended but when added with -pedantic, it won't compile. I'm still quite a beginner in programming and it is the first time I encountered this problem so it is quite a problem to me.

Here is the code that is causing the error:

char *exercise[5]={"swimming", "running", "brisk walking", "weight lifting", "zumba"};

I'd appreciate it if you would explain what the solution is instead of just the fixed code because I want to learn.

1条回答
甜甜的少女心
2楼-- · 2019-08-13 19:16

This has nothing to do with arrays specifically. The original version of standardized C language (ISO C90) forbids mixing declarations and code.

In C90 each local block surrounded by {} has rather strict structure: it begins with declarations (if any), which are then followed by statements (code).

That is the format you have to follow. Move your array declaration to the top of the block. It should be trivial, since none of your initializers depend on any run-time calculations. That's all there is to it.

{
  /* Declarations go here */
  char *exercise[5]={"swimming", "running", "brisk walking", "weight lifting", "zumba"};

  /* Statements (i.e. code) goes here */
}

Of course, the unspoken question here is: do you really have to use C90? Were you explicitly asked to write your code for C90 compiler? Maybe you should simply switch your compiler to C99 mode and forget about this C90-specific restriction?

In newer versions of C language (C99 and later) you can freely mix statements and declarations. GCC can be switched to C99 mode by specifying -std=c99 in command line.

查看更多
登录 后发表回答