简体   繁体   中英

Does C11 allow variable declarations at any place in a function?

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?

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

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 .

Note that you cannot put a declaration immediately after a label (C11 §6.8.1 Labelled statements ); you cannot label a declaration, or jump to a declaration. See also §6.8.2 Compound statement , §6.7 Declarations and §6.9 External definitions . However, you can label an empty statement, so it isn't a major problem:

label: ;
    int a = 5;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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