Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 380
Amir Saniyan Avatar asked Dec 07 '22 11:12

Amir Saniyan


2 Answers

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

like image 85
rubenvb Avatar answered Dec 09 '22 00:12

rubenvb


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;
like image 44
Jonathan Leffler Avatar answered Dec 09 '22 01:12

Jonathan Leffler