简体   繁体   English

由于数组,ISO C90禁止混合声明和代码。 我该如何解决?

[英]ISO C90 forbids mixed declarations and code because of arrays. How do I fix this?

I tried compiling it using -gcc and it worked as intended but when added with -pedantic , it won't compile. 我尝试使用-gcc编译,并且按预期工作,但是与-pedantic一起添加时,它将无法编译。 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. 如果您能解释解决方案而不是固定代码,因为我想学习,我将不胜感激。

This has nothing to do with arrays specifically. 这与数组无关。 The original version of standardized C language (ISO C90) forbids mixing declarations and code. 标准化C语言(ISO C90)的原始版本禁止混合声明和代码。

In C90 each local block surrounded by {} has rather strict structure: it begins with declarations (if any), which are then followed by statements (code). 在C90中,每个用{}包围的局部块具有相当严格的结构:它以声明(如果有的话)开头,然后是语句(代码)。

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? 当然,这里不为人知的问题是:您真的必须使用C90吗? Were you explicitly asked to write your code for C90 compiler? 您是否明确要求为C90编译器编写代码? Maybe you should simply switch your compiler to C99 mode and forget about this C90-specific restriction? 也许您应该只将编译器切换到C99模式,而忘记此C90特定的限制?

In newer versions of C language (C99 and later) you can freely mix statements and declarations. 在较新版本的C语言(C99和更高版本)中,您可以自由地混合使用语句和声明。 GCC can be switched to C99 mode by specifying -std=c99 in command line. 通过在命令行中指定-std=c99 ,可以将GCC切换到C99模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM