Skip to content
Tutorials Center
My learning

Topics

Lesson 106 of 135 ยท Advanced C

_Static_assert and C23 Attributes

Catch bugs at compile time in C with static_assert, and use C23 attributes such as nodiscard, deprecated, maybe_unused, fallthrough, noreturn and has_c_attribute.

The cheapest bug to fix is the one the compiler refuses to build. C gives you two tools for moving checks from "the program crashed at 3 a.m." to "the build failed on my laptop": static_assert, which verifies a fact about your code while compiling, and attributes, small annotations such as [[nodiscard]] that tell the compiler what a function or variable means so it can warn about misuse.

This lesson covers both. You will learn the syntax of static_assert (and its older spelling _Static_assert), where it can go, which expressions it accepts and how it differs from the runtime assert. Then you will meet the C23 attribute syntax [[...]], the standard attributes, how to ask whether the compiler supports one, and how to write headers that still compile on older compilers. Our editor compiles with -std=c23 -Wall -Wextra, so everything here runs as shown. It helps to know constants, padding and alignment and conditional compilation. A shorter tour of C23 appears in Modern C.

static_assert

A static assertion has a condition and, optionally, a message:

C
static_assert(sizeof(int) >= 4, "this code needs 32-bit ints");
static_assert(sizeof(int) >= 4);          // C23: the message is optional

The condition must be an integer constant expression: something the compiler can calculate itself, such as sizeof, offsetof, CHAR_BIT, enumeration constants, constexpr variables and arithmetic on them. If the condition is false, compilation stops with an error that shows your message:

TEXT
main.c:5:1: error: static assertion failed: "this code needs 32-bit ints"

If it is true, the assertion generates no code at all and costs nothing at runtime.

A little history explains the two spellings. C11 introduced the keyword _Static_assert, and <assert.h> defines the friendlier macro static_assert for it (so before C23 you write #include <assert.h>). C23 promotes static_assert to a real keyword and makes the message optional. In a C23 program you can use static_assert without including anything.

Unlike the runtime assert, a static assertion can appear anywhere a declaration can: at file scope, inside a function, or even inside a struct or union. It cannot use values that are only known when the program runs, so static_assert(argc > 1) is an error.

flowchart TD
    A["A condition you rely on"] --> B{"Known at<br/>compile time?"}
    B -->|"yes: sizes, offsets,<br/>constants, enum counts"| C["static_assert<br/>build fails if wrong"]
    B -->|"no: depends on data"| D{"Can bad input<br/>happen in real use?"}
    D -->|"yes: files, users, network"| E["check and handle the error"]
    D -->|"no: it is a programmer mistake"| F["assert<br/>debug-build check"]

Choose the earliest tool that can see the problem. A failed static assertion costs one compile; a failed runtime check costs a user.

What to assert

The best static assertions record an assumption that your code silently depends on. The first example collects five typical ones:

C Compile-time facts about sizes, layout and tables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

All assertions pass, so the program just prints its facts. Now imagine adding YELLOW to the enum: the table assertion fails at once and points to the line, instead of letting color_names[YELLOW] read past the end of the array. Or imagine a colleague inserting a uint8_t field into Header: the layout assertions catch it before a corrupted file ever exists. See padding and alignment for why layouts are fragile.

A few more useful idioms:

  • Pin down a type's range before relying on it: static_assert(sizeof(size_t) >= 8, "needs a 64-bit build").
  • Document the maximum of a counter: static_assert(MAX_USERS <= UINT16_MAX).
  • Check generic code: static_assert(_Generic((x), int: 1, default: 0), "x must be an int"), combining with _Generic.
  • Reject impossible settings from #defines that users can override on the command line, for example static_assert((CACHE_SIZE & (CACHE_SIZE - 1)) == 0, "CACHE_SIZE must be a power of two").

Assertions are checked at compile time only. They cannot protect against values that come from files, user input or function arguments. For those, use ordinary error handling (see error handling).

Attributes

An attribute is extra information attached to a declaration. It does not change what the program computes, but it lets the compiler warn you, optimize or document your intent. Before C23 every compiler had its own syntax (__attribute__((...)) in GCC and Clang, __declspec(...) in MSVC). C23 standardizes the C++-style double-bracket syntax:

C
[[nodiscard]] int open_config(const char *path);

An attribute can appear in several places, and it applies to the thing next to it:

Position Applies to Example
Before a declaration the declared entity [[deprecated]] void old_api(void);
After the declared name that entity int counter [[maybe_unused]];
After struct, union, enum the type struct [[nodiscard]] Result { int code; };
Before a parameter that parameter int f([[maybe_unused]] int flags)
On its own statement the statement [[fallthrough]];

Some attributes take arguments in parentheses: [[deprecated("use open_config instead")]]. A list uses commas: [[nodiscard, deprecated]]. Vendor attributes are written with a prefix, such as [[gnu::always_inline]], so they never clash with the standard names. A compiler must ignore an attribute it does not recognize (usually with a warning under -Wall), so adding attributes does not break builds on other compilers.

The standard attributes

C23 defines these:

Attribute Meaning
[[nodiscard]] or [[nodiscard("reason")]] Warn if the caller ignores the result. For a function; or for a type, warn when any function returning that type has its result dropped.
[[maybe_unused]] Do not warn if this variable, parameter, function or type ends up unused.
[[deprecated]] or [[deprecated("reason")]] Warn on every use. The message tells people what to do instead.
[[fallthrough]] In a switch, "yes, I meant to continue into the next case".
[[noreturn]] This function never returns (it exits or loops forever). It replaces the old _Noreturn keyword.
[[reproducible]], [[unsequenced]] Promises that a function is a pure computation (see below). They go after the parameter list.

The next example uses most of them. Compile and run it, then read the compiler's warnings. Each warning is the attribute doing its job:

C Attributes in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The program runs and prints its lines. Look at the compiler messages (they appear while building, before the program output):

TEXT
main.c:..: warning: ignoring return value of 'parse_port', declared with attribute 'nodiscard': "a failed parse must be handled"
main.c:..: warning: 'legacy_port' is deprecated: use parse_port instead
main.c:..: warning: ignoring return value of type 'struct Status', declared with attribute 'nodiscard'

A few details are worth noticing:

  • [[nodiscard]] is for results that matter. Error codes, allocated pointers, handles that must be released, and the return value of pure functions all deserve it. A cast to (void) is the standard way to say "I know, and I am ignoring it on purpose".
  • [[maybe_unused]] quiets warnings for parameters required by a callback signature, for variables used only inside assert (which disappears in release builds), and for functions that exist only in some configurations.
  • [[fallthrough]] must be directly followed by the next case label. With -Wextra the compiler warns about a case that runs into the next one without it, so the attribute marks the deliberate cases and exposes the accidental ones.
  • [[noreturn]] tells the compiler that nothing follows the call, so describe needs no return after fatal(...) and there is no "control reaches end" warning. Marking a function [[noreturn]] that does return is undefined behavior.
  • [[deprecated]] is how a library retires a function gently: the old name keeps working and every caller sees the message.

reproducible and unsequenced

C23 adds two attributes that describe pure functions, which helps the optimizer reuse results:

  • [[reproducible]] means that calling the function twice with the same arguments and the same global state gives the same result and has no observable side effects, apart from reading memory.
  • [[unsequenced]] is stricter: the function is stateless; the result depends only on the argument values and nothing else.

They go after the parameter list, because they describe the function type:

C
int square(int x) [[unsequenced]];
size_t count_vowels(const char *text) [[reproducible]];

Use them sparingly. If the function does not keep the promise, the program has undefined behavior. A function that prints, modifies a global or reads the clock is neither. They are a niche tool for numerical and library code; [[nodiscard]], [[maybe_unused]] and [[deprecated]] matter far more in everyday programs.

Is the attribute supported?

C23 adds the operator __has_c_attribute(name) for #if. It gives 0 for an unknown attribute and a date such as 202311 for a supported standard one, so you can write headers that adapt to the compiler. This lets code keep working with older compilers (C11 and C17 do not know [[...]] at all):

C Using attributes safely on any compiler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Every standard attribute reports 202311 (the month C23 was published), the unknown one reports 0, and the program compiles identically on a compiler that predates C23 by falling back to GCC's __attribute__ or to nothing. Wrapping attributes in macros like NODISCARD is the standard way to keep a code base portable across compilers.

Vendor attributes worth knowing

Attributes in the gnu:: namespace work in GCC and Clang. A few are very practical:

  • [[gnu::format(printf, 1, 2)]] on a logging function makes the compiler check its format string against the arguments, exactly like it does for printf itself.
  • [[gnu::always_inline]] and [[gnu::noinline]] control inlining.
  • [[gnu::cold]] marks error paths so the optimizer keeps them out of the way.
  • [[gnu::packed]] removes struct padding (use with care; unaligned access can be slow or fault on some CPUs, and the layout is better pinned down with static_assert).
  • [[gnu::aligned(64)]] raises an alignment, for example to a cache line.

Because they are vendor-specific, wrap them in macros that expand to nothing elsewhere, as in the example above.

Good habits

  • Add a static_assert whenever code depends on a size, a layout or the length of a table. It documents the assumption and enforces it.
  • Mark functions that return error codes [[nodiscard]], and deprecate rather than delete old APIs.
  • Write a reason in deprecated and nodiscard messages: the message is the documentation the developer reads in the compiler output.
  • Keep -Wall -Wextra on, since most attribute benefits appear as warnings, and treat warnings as errors in CI.
  • Never rely on an attribute to change program meaning. Removing every attribute should leave a program that behaves the same (except for noreturn, reproducible and unsequenced, which are promises you must keep).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What kind of condition does static_assert accept?

    The compiler must be able to compute the condition itself. sizeof and offsetof are common, but constants, enums and constexpr values also work.
  2. 2. What is the difference between assert and static_assert?

    static_assert fails the build when its condition is false and generates no code. assert checks runtime conditions (and disappears with NDEBUG).
  3. 3. A function is declared [[nodiscard]] int save(void);. What happens when you call save(); and ignore the result?

    nodiscard asks the compiler to warn when the result is ignored. Writing (void)save(); says the ignoring is intentional.
  4. 4. Where does [[fallthrough]] go?

    [[fallthrough]]; is a standalone statement placed where one case runs into the next, so a deliberate fall-through is marked and accidental ones are still warned about.
  5. 5. What does __has_c_attribute(made_up_name) evaluate to in a C23 compiler?

    The operator yields 0 for an attribute the compiler does not know, and a date value for a supported standard attribute, so it can be used in #if.

Summary

  • static_assert(condition, "message") verifies an integer constant expression while compiling; in C23 it is a keyword and the message is optional. It works at file, block and struct scope and produces no code.
  • Use it for platform assumptions, struct layouts (offsetof, sizeof), enum-to-table lengths and relationships between configuration constants.
  • C23 attributes use [[name]] or [[name("text")]]; vendor attributes use a prefix like gnu::, and unknown attributes are ignored.
  • The standard set is nodiscard, maybe_unused, deprecated, fallthrough, noreturn, plus the pure-function promises reproducible and unsequenced.
  • __has_c_attribute(name) lets headers adapt to older compilers; wrap attributes in macros with fallbacks for portability.
  • Attributes mostly produce helpful warnings, so keep -Wall -Wextra enabled and fix what they report.

Next: Project: Command Calculator