The function specifier _Noreturn
was introduced in C11. The header <stdnoreturn.h>
provides a macro noreturn
which expands to _Noreturn
. So using _Noreturn
or noreturn
from <stdnoreturn.h>
is fine and equivalent.
A function that's declared with _Noreturn
(or noreturn
) is not allowed to return to its caller. If such a function does return to its caller, the behavior is undefined.
In the following example, func()
is declared with noreturn
specifier but it returns to its caller.
#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;
}
gcc
and clang
produce warnings for the above program:
$ 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]
}
^
An example using noreturn
that has well-defined behavior:
#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;
}