楼主:
PkmX (阿猫)
2016-05-09 14:11:58其实 static 在 C99 之后还有一个鲜少人知道的用法:
#include <stddef.h>
void foo(int a[static 42]) {}
int main(void)
{
int x[41], y[42], z[43];
foo(x);
foo(y);
foo(z);
foo(NULL);
return 0;
}
$ clang -std=c11 -Wall -Wextra -pedantic -fsyntax-only main.c
main.c:8:5: warning: array argument is too small; contains 41 elements,
callee requires at least 42 [-Warray-bounds]
foo(x);
^ ~
main.c:3:14: note: callee declares array parameter as static here
void foo(int a[static 42]) {}
^~~~~~~~~~~~
main.c:11:5: warning: null passed to a callee that requires a non-null
argument [-Wnonnull]
foo(NULL);
^ ~~~~
main.c:3:14: note: callee declares array parameter as static here
void foo(int a[static 42]) {}
^~~~~~~~~~~~
顺带一题,修饰 array 参数的 qualifier 也是写在 [] 里面,
所以一个 function 的宣告可能可以长成这个样子:
void foo(int a[static const restrict 42], int b[static const restrict 42]);
另外因为标准规定只有 static <qualifier> 或 <qualifier> static 两种写法,
所以不能写 const static restrict,这里 clang 会喷一个令人摸不著头绪的错误:
error: expected expression
void foo(int a[const static restrict 42]) {
^
看到这里有没有觉得 C 语言真的是很亲切呢^^