Re: [问题] uses of the keyword static

楼主: 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 语言真的是很亲切呢^^
作者: ian031545 (IanTsaiTW)   2016-05-09 14:25:00
作者: VictorTom (鬼翼&娃娃鱼)   2016-05-09 23:50:00
作者: wtchen (没有存在感的人)   2016-05-10 00:53:00
所以引数为static的用途是?
作者: Frozenmouse (*冰之鼠*)   2016-05-10 12:54:00
看错误讯息应该是要至少传int[n], n>=42
作者: james732 (好人超)   2016-05-10 13:18:00
第一次看到这种写法orz
作者: bibo9901 (function(){})()   2016-05-10 13:44:00
我也是第一次看到XD cool

Links booklink

Contact Us: admin [ a t ] ucptt.com