Does C11 allow variable declarations at any place

2019-02-25 00:14发布

问题:

Does the C11 standard (note I don't mean C++11) allow you to declare variables at any place in a function?

The code below is not valid in 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;
}

Is it valid source code in C11?

回答1:

Yes. This was already valid in C99 (see the second bullet here).



回答2:

More or less. C99 introduced the ability to declare variables part way through a block and in the first section of a for loop, and C2011 has continued that.

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;
    }
}

You might also note that the C++ style tail comments are only valid in C99 or later, too.

If you have to deal with C compilers that are not C99 compliant (MSVC, for example), then you can't use these (convenient) notations. GCC provides you with a useful warning flag: -Wdeclaration-after-statement.