是否允许C11变量声明在函数的任何地方吗?(Does C11 allow variable decl

2019-07-02 19:54发布

请问C11标准(注意我说的不是C ++ 11)允许你在函数的任何地方声明变量?

下面的代码是不是在ANSI C(C89,C90)有效:

int main()
{
  printf("Hello world!");
  int a = 5; /* Error: all variables should be declared at the beginning of the function. */
  return 0;
}

它是在C11有效的源代码?

Answer 1:

是。 这已经在C99有效(见第二子弹这里 )。



Answer 2:

或多或少。 C99引入了通过一个块中的第一部分来声明变量部分道路的能力for循环,C2011还继续说。

void c99_or_later(int n, int *x)
{
    for (int i = 0; i < n; i++)  // C99 or later
    {
         printf("x[%d] = %d\n", i, x[i]);
         int t = x[i];           // C99 or later
         x[0] = x[i];
         x[i] = t;
    }
}

你可能也注意到,C ++风格的尾部评论仅在C99或更高版本有效,太。

如果你要处理的C编译器是不符合C99(MSVC,例如),那么你就不能使用这些(方便)符号。 GCC为您提供了一个有用的警告标志: -Wdeclaration-after-statement



文章来源: Does C11 allow variable declarations at any place in a function?