Re: [問題] uses of the keyword static

看板C_and_CPP作者 (阿貓)時間9年前 (2016/05/09 14:12), 9年前編輯推噓5(501)
留言6則, 6人參與, 最新討論串3/3 (看更多)
其實 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://www.ptt.cc/bbs/C_and_CPP/M.1462774321.A.69B.html ※ 編輯: PkmX (140.113.193.217), 05/09/2016 14:21:00

05/09 14:25, , 1F
05/09 14:25, 1F
※ 編輯: PkmX (140.113.193.217), 05/09/2016 14:32:07

05/09 23:50, , 2F
05/09 23:50, 2F

05/10 00:53, , 3F
所以引數為static的用途是?
05/10 00:53, 3F

05/10 12:54, , 4F
看錯誤訊息應該是要至少傳int[n], n>=42
05/10 12:54, 4F

05/10 13:18, , 5F
第一次看到這種寫法orz
05/10 13:18, 5F

05/10 13:44, , 6F
我也是第一次看到XD cool
05/10 13:44, 6F
文章代碼(AID): #1NC2enQR (C_and_CPP)
文章代碼(AID): #1NC2enQR (C_and_CPP)