This C99 notation, void foo(double A[static 10])
, means that the function can assume that A
points to 10 valid arguments (from *A
to A[9]
). The notation makes programs more informative, helping compilers to both optimize the code generated for the function foo
and to check that it is called correctly at each call site.
In the C99 standard, in which the notation was introduced, this is covered by clauses 6.7.5.2 and 6.7.5.3:7.
“… If the keyword static also appears within the [ and ] of the array type derivation, then for each call to the function, the value of the corresponding actual argument shall provide access to the first element of an array with at least as many elements as specified by the size expression”
One common use is f(int p[static 1])
, which is more or less equivalent to the notion of reference (as opposed to pointer) in other languages. Clang warns if such a function was declared and is passed a null pointer at the call site (because the notation explicitly means that p
will not be NULL
). However, the last time I tried, Clang did not warn for f(&a + 1)
, which is a shame (but a compiler doesn't have to emit all warnings. Emitting some warnings is good already):
#include <stdio.h>
void f(int p[static 1])
{
printf("%d
", *p);
}
int main(){
int a = 0;
f(&a + 1);
f(0);
f(&a);
}
Clang warns for the second call, but unfortunately not for the first one:
$ clang t.c
t.c:11:3: warning: null passed to a callee which requires a non-null argument
[-Wnonnull]
f(0);
^ ~
t.c:3:12: note: callee declares array parameter as static here
void f(int p[static 1])
^~~~~~~~~~~
1 warning generated.
The syntax may seem a little strange, but the C99 standardization committee obviously decided to reuse the pre-existing static
keyword in a place that did not cause ambiguity so as to avoid the introduction of a new keyword (that could possibly break existing programs).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…