從使用 Noreturn 或 noreturn 函式說明符宣告的函式返回

Version >= C11

函式說明符 _Noreturn 是在 C11 中引入的。標頭檔案 <stdnoreturn.h> 提供了一個巨集 noreturn,它擴充套件為 _Noreturn。因此,使用 <stdnoreturn.h> 中的 _Noreturnnoreturn 很好並且相當。

使用 _Noreturn(或 noreturn)宣告的函式不允許返回其呼叫者。如果此類函式確實返回其呼叫者,則行為未定義。

在以下示例中,func() 使用 noreturn 說明符宣告,但它返回其呼叫者。

#include <stdio.h>
#include <stdlib.h>
#include <stdnoreturn.h>

noreturn void func(void);

void func(void)
{
    printf("In func()...\n");
} /* Undefined behavior as func() returns */

int main(void)
{
    func();
    return 0;
}

gccclang 為上述程式發出警告:

$ gcc test.c
test.c: In function ‘func’:
test.c:9:1: warning: ‘noreturn’ function does return
 }
 ^
$ clang test.c
test.c:9:1: warning: function declared 'noreturn' should not return [-Winvalid-noreturn]
}
^

使用具有明確定義行為的 noreturn 的示例:

#include <stdio.h>
#include <stdlib.h>
#include <stdnoreturn.h>

noreturn void my_exit(void);

/* calls exit() and doesn't return to its caller. */
void my_exit(void)
{
    printf("Exiting...\n");
    exit(0);
}

int main(void)
{
    my_exit();
    return 0;
}