问题
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:
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.
来源:https://stackoverflow.com/questions/25346592/iso-c90-forbids-mixed-declarations-and-code-because-of-arrays-how-do-i-fix-this