Reputation: 13739
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?
Upvotes: 4
Views: 2518
Reputation: 754030
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;
Upvotes: 5