作者PkmX (阿猫)
看板C_and_CPP
标题Re: [问题] uses of the keyword static
时间Mon May 9 14:11:58 2016
其实 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 语言真的是很亲切呢^^
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 140.113.193.217
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1462774321.A.69B.html
※ 编辑: PkmX (140.113.193.217), 05/09/2016 14:21:00
1F:推 ian031545: 强 05/09 14:25
※ 编辑: PkmX (140.113.193.217), 05/09/2016 14:32:07
2F:推 VictorTom: 推 05/09 23:50
3F:推 wtchen: 所以引数为static的用途是? 05/10 00:53
4F:推 Frozenmouse: 看错误讯息应该是要至少传int[n], n>=42 05/10 12:54
5F:推 james732: 第一次看到这种写法orz 05/10 13:18
6F:→ bibo9901: 我也是第一次看到XD cool 05/10 13:44