Skip to content
systemcoding.dev
Toolchains

Mark Functions That Never Return With the noreturn Attribute

Declare a function that calls exit or abort as noreturn so GCC drops dead code, silences false warnings and lays out the error path correctly.

6 min read
Summarize in AI
Flat illustration of an editor window full of code, with the GNU, C and C++ logos.

Some functions do not come back. exit ends the process, abort raises a signal, longjmp jumps somewhere else, and a function that loops forever waiting for an interrupt never returns either. The compiler cannot guess this from a prototype, because a prototype says only what the function takes and what it yields. The noreturn attribute is how you tell it. This post shows the smallest working example, what the compiler does differently once it knows, the standard spellings in C11 and C23, and the one mistake that turns a helpful annotation into a bug. The examples use GCC 14 and apply equally to Clang 18.

The problem noreturn solves

Suppose a program has a helper that prints an error and exits, and a caller that uses it:

noattr.cc
#include <stdio.h>
#include <stdlib.h>

void die(const char *msg)
{
    fprintf(stderr, "fatal: %s\n", msg);
    exit(1);
}

int first_digit(const char *s)
{
    if (s[0] >= '0' && s[0] <= '9')
        return s[0] - '0';
    die("not a digit");
}

Compile with warnings turned on:

Shell
gcc -Wall -Wextra -c noattr.c
Text
noattr.c: In function 'first_digit':
noattr.c:15:1: warning: control reaches end of non-void function [-Wreturn-type]

The warning is a false alarm, since die exits. The compiler does not know that, because die is a normal function that, as far as the declaration says, could return. In a large code base these warnings pile up, and people respond by adding a dummy return 0; after the call, which is dead code that hides real mistakes later.

Adding the attribute

Place noreturn on the declaration. In GNU C the spelling is __attribute__((noreturn)):

withattr.cc
#include <stdio.h>
#include <stdlib.h>

__attribute__((noreturn)) void die(const char *msg);

void die(const char *msg)
{
    fprintf(stderr, "fatal: %s\n", msg);
    exit(1);
}

int first_digit(const char *s)
{
    if (s[0] >= '0' && s[0] <= '9')
        return s[0] - '0';
    die("not a digit");
}
Shell
gcc -Wall -Wextra -c withattr.c

The compile now prints nothing. The compiler knows control cannot pass the call to die, so the end of the function is unreachable and no return value is missing. The attribute also works in two further ways that matter beyond the warning.

First, the compiler removes code after a noreturn call. Anything following it in the same block is unreachable and is deleted. Second, it treats the branch that contains the call as cold. A branch that ends in a function that never returns is almost certainly an error path, so GCC moves the call out of the fall-through sequence and lays the common path out contiguously. You get a small but real improvement in instruction-cache use for free.

The standard spellings

C11 introduced the keyword _Noreturn and a header macro noreturn in <stdnoreturn.h>:

c
#include <stdnoreturn.h>

noreturn void die(const char *msg);

C23 deprecates both in favor of the attribute syntax and makes [[noreturn]] standard:

c
[[noreturn]] void die(const char *msg);

GCC 13 and later accept the C23 form with -std=c23, and GCC accepts [[noreturn]] as an extension in earlier modes with a pedantic warning. Clang 15 and later support it as well. The GNU __attribute__((noreturn)) works in every mode and every GCC release, and it is what to use in a header that has to compile for older toolchains. The C++ equivalent is [[noreturn]] from C++11.

Whichever you pick, wrap it in a macro in one header so the spelling is changed in one place:

common.hc
#if defined(__GNUC__) || defined(__clang__)
#define NORETURN __attribute__((__noreturn__))
#elif defined(_MSC_VER)
#define NORETURN __declspec(noreturn)
#else
#define NORETURN
#endif

MSVC spells the same idea __declspec(noreturn), which is why the macro has a branch for it.

What counts as never returning

A noreturn function must leave the caller's flow by some route other than a return. Valid ways to do that are:

  1. Calling exit, _exit, abort or quick_exit, or another noreturn function.

  2. Calling longjmp or siglongjmp, which transfers control to a saved context.

  3. Looping forever, as for (;;) { wfi(); } does in a bare-metal fault handler.

  4. Ending the thread with pthread_exit, or terminating via execve when it succeeds. A function that calls execve and handles its failure by calling _exit qualifies.

  5. Throwing a C++ exception, which leaves the function without returning normally.

A function that calls exit only on some paths does not qualify. GCC helps here: if it can see that a noreturn function can reach a return, it warns.

bad.cc
#include <stdlib.h>

__attribute__((noreturn)) void maybe_die(int code)
{
    if (code != 0)
        exit(code);
}
Text
bad.c: In function 'maybe_die':
bad.c:7:1: warning: 'noreturn' function does return

That warning is the compiler catching the one mistake that matters. If you ignore it, the generated code has no return instruction on the path where code is zero, and execution continues into whatever machine code follows the function in memory. The result is a crash or something worse, and it appears far from the cause. Treat this warning as an error.

A realistic error helper

In practice you add a printf-style format and make the helper variadic, so one function reports any fatal condition. Combine noreturn with format so format mistakes are caught too:

fatal.cc
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>

__attribute__((noreturn, format(printf, 1, 2)))
void fatal(const char *fmt, ...);

void fatal(const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    fputs("fatal: ", stderr);
    vfprintf(stderr, fmt, ap);
    fputc('\n', stderr);
    va_end(ap);
    exit(2);
}

int parse_port(const char *s)
{
    char *end;
    long v = strtol(s, &end, 10);
    if (*end != '\0' || v < 1 || v > 65535)
        fatal("bad port '%s'", s);
    return (int)v;
}

int main(void)
{
    printf("%d\n", parse_port("8080"));
    printf("%d\n", parse_port("99999"));
    return 0;
}

Running it prints the first port, then the error on standard error and exits with status 2 before the second printf runs:

Text
8080
fatal: bad port '99999'

Because fatal is noreturn, the compiler does not require a return statement on the failing path of parse_port, and it moves the call out of the likely path. Because it also has the format attribute, a call like fatal("bad port %d", s) with a string argument would be reported at compile time.

Interactions to know about

noreturn and inlining work together: a function marked noreturn can still be inlined, and the inlined copy keeps the "no fall-through" property. noreturn and -fno-exceptions in C++ differ in that a noreturn function may still throw. Profilers and debuggers show a call to a noreturn function as a call with no matching return, so stack traces end there, which is what you want.

Tail calls interact in one more way. A function that ends by calling a noreturn function does not need a stack frame to return through, so GCC can emit a plain jmp. This is why a noreturn handler shows up as a jump in disassembly, and it is also why the stack trace may omit the caller. Compile with -fno-optimize-sibling-calls when you need frames for debugging.

When not to use it

Do not mark a function noreturn because it currently happens to exit. Mark it because that is its contract. A function that today calls exit and tomorrow tries to recover from the failure must lose the attribute at the same time, and nothing will force you to remember. Also avoid it on functions that may return an error to some callers through a return value, on callback pointers whose targets you do not control, and on virtual functions where an override might return. Finally, a function that calls longjmp into a context created by setjmp in an ancestor frame is noreturn from the caller's view, and that works, but code that uses setjmp in the same function is better served by restructuring.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.