函式說明符
來自 cppreference.com
用於函式宣告中。
本節不完整 原因:拆分為兩個頁面 |
inline
(C99 起) - 建議編譯器“內聯”函式,使其調用盡可能快。_Noreturn
(C11 起) - 指定函式不會返回到其被呼叫的位置。
目錄 |
[編輯] 語法
inline function_declaration | |||||||||
_Noreturn function_declaration | |||||||||
[編輯] 解釋
[編輯] inline (C99 起)
inline
關鍵字是給編譯器的一個提示,用於執行最佳化。編譯器可以自由地忽略此請求。
如果編譯器行內函數,它會將該函式的每次呼叫替換為實際的函式體(不生成呼叫)。這避免了函式呼叫產生的額外開銷(將資料放入堆疊並檢索結果),但它可能會導致可執行檔案更大,因為函式的程式碼必須重複多次。結果類似於函式式宏。
函式體必須在當前翻譯單元中可見,這使得 inline
關鍵字對於在標頭檔案中實現函式是必需的,即無需編譯和連結的原始檔。
[編輯] inline 示例
關閉內聯時,執行時間約為 1.70 秒。開啟內聯時,執行時間不到一秒。
執行此程式碼
/* inline int sum(int a, int b) { return (a + b); } int c = sum(1, 4); // If the compiler inlines the function the compiled code will be the same as writing: int c = 1 + 4; */ #include <stdio.h> #include <stdlib.h> #include <time.h> /* int sum (int a, int b) __attribute__ ((noinline)); */ static inline int sum (int a, int b) { return a+b; } int main(void) { const int SIZE = 100000; int X[SIZE],Y[SIZE],A[SIZE]; int i,j; for (i=0;i<SIZE;++i) { X[i] = rand(); Y[i] = rand(); } clock_t t = clock(); /* start clock */ for (i=0;i<5000;++i) { for (j=0;j<SIZE;++j) A[j] = sum(X[j],Y[j]); } t = clock()-t; /* stop clock */ printf("Time used: %f seconds\n", ((float)t)/CLOCKS_PER_SEC); printf("%d\n", A[0]); return EXIT_SUCCESS; }
可能的輸出
Time used: 0.750000 seconds -1643747027
[編輯] _Noreturn (C11 起)
_Noreturn
關鍵字表示其後的函式不會返回到呼叫它的函式。如果宣告為 _Noreturn
的函式嘗試返回值,編譯器通常會生成警告。
在下面的示例中,呼叫了 stop_now() 函式,這會導致程式立即終止(除非捕獲到 SIGABRT
訊號)。呼叫 stop_now() 之後的 printf() 和 return EXIT_SUCCESS; 的程式碼永遠不會執行,並且執行永遠不會返回到呼叫 stop_now() 的 main() 函式。
[編輯] _Noreturn 示例
執行此程式碼
#include <stdlib.h> #include <stdio.h> _Noreturn void stop_now() { abort(); } int main(void) { printf("Preparing to stop...\n"); stop_now(); printf("This code is never executed.\n"); return EXIT_SUCCESS; }
輸出
Preparing to stop... Abort