What's the point of declaration for formal parameters within the function prototype scope in C?
From my own test, it seems that the point of declaration for formal parameters in the prototype scope follows a left-to-right order (parameter name becomes visible within the prototype scope in left-to-right order), but I'm not sure. Could you kindly explain this or point me to the right place?
case 1: no complaints from gcc with c99 standard
int sum(int n, int a[n]);
case 2: "error: ‘n’ undeclared here (not in a function)" from gcc with c99 standard
int sum(int a[n], int n);
Both of the above cases are placed under a file scope with no variable named n in the file scope.
CodePudding user response:
The C standard does not define a “point of declaration.” It defines scope, which is the region of program text in which it is visible (can be used) (C 2018 6.2.1 2).
C 2018 6.2.1 7 says:
… Any other identifier [the previous text covers structure/union/enumeration tags and enumeration constants] has scope that begins just after the completion of its declarator.
Therefore, in int sum(int n, int a[n]);
, the scope of n
begins at the ,
, and the scope of a
begins at the )
(because [n]
is part of its declarator).
In int sum(int a[n], int n);
, the scope of n
has not begun where a[n]
appears.
Bonus
Observe that in this code, the scope of the parameter a
does not begin until after int (*a)[a]
, so the a
in [a]
refers to the prior a
, and the program prints “*a's type has 3 elements.”:
#include <stdio.h>
int a = 3;
static void f(int (*a)[a])
{
printf("*a's type has %zu elements.\n", sizeof *a / sizeof **a);
}
int main(void)
{
f(0);
}