Skip to content
systemcoding.dev
Toolchains

Use Standard Attributes Like [[nodiscard]] and [[maybe_unused]]

Replace GNU attribute spellings with standard [[nodiscard]], [[maybe_unused]], [[deprecated]] and [[fallthrough]] in C23 and C++17, and see what GCC reports.

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

For decades, annotating a C function meant __attribute__((...)) on GCC and Clang, __declspec(...) on MSVC and nothing at all on anything else. C++11 introduced a standard syntax, double square brackets, and C++17 and C++20 filled it with attributes that mean the same on every conforming compiler. C23 brought the same syntax and several of the same attributes to C. This post shows the four you will use daily, [[nodiscard]], [[maybe_unused]], [[deprecated]] and [[fallthrough]], with the warnings GCC 14 produces, the version where each became available, and the differences from the GNU spellings you may have used before. The point is practical: where your toolchain allows it, the standard forms remove a layer of macros.

The syntax and where attributes go

An attribute specifier is [[name]] or [[name(arguments)]], and it attaches to the entity it is next to. Placed before a declaration it applies to what is declared. Placed after a declarator name it applies to that entity. Placed on its own with a semicolon, [[fallthrough]];, it forms an attribute statement. Compilers must ignore attributes they do not recognize, with at most a warning, which makes the syntax safe on older tools, though an ignored [[nodiscard]] protects nothing. Vendor attributes use a namespace prefix: [[gnu::cold]], [[clang::always_inline]].

C23, which GCC supports with -std=c23 from version 13 (and with -std=c2x for part of the set from earlier releases), standardizes [[deprecated]], [[fallthrough]], [[maybe_unused]], [[nodiscard]] and [[noreturn]], and adds [[unsequenced]] and [[reproducible]]. C++ has all of these from C++11 to C++17, with [[likely]] and [[unlikely]] in C++20.

nodiscard: do not ignore this result

[[nodiscard]] on a function asks the compiler to warn when a caller ignores the return value. It exists for functions whose result carries an error or a resource:

nd.cc
#include <stdio.h>

[[nodiscard]] int open_config(const char *path)
{
    return path[0] == '/' ? 0 : -1;
}

int main(void)
{
    open_config("/etc/app.conf");
    int rc = open_config("relative");
    printf("%d\n", rc);
    return 0;
}

Compile with gcc -std=c23 -Wall nd.c:

Text
nd.c: In function 'main':
nd.c:10:5: warning: ignoring return value of 'open_config' declared with attribute 'nodiscard' [-Wunused-result]

The second call stores the result, so it is accepted. In C23 and C++20 you can attach a reason that appears in the diagnostic, [[nodiscard("check the error code")]]; C++17 accepts only the bare form. To say "I know, ignore it deliberately", cast the call to void:

c
(void)open_config("/etc/app.conf");

That cast silences [[nodiscard]], and it does not silence the GNU warn_unused_result, which GCC treats more strictly. This difference is the main reason to prefer the standard attribute when you want a deliberate ignore to be possible.

[[nodiscard]] applies to types as well. In C23 and C++17 you can mark a struct, union or enum so that any function returning it is treated as nodiscard:

c
[[nodiscard]] typedef struct { int code; } result_t;

The standard C++ library uses this heavily: std::vector::empty() is [[nodiscard]], so v.empty(); as a statement, a common mistake for v.clear(), produces a warning.

maybe_unused: say the unused thing is intentional

-Wunused-parameter, -Wunused-variable and -Wunused-function catch dead names, and a few of those names exist on purpose: a callback parameter your implementation ignores, a variable used only in an assert that compiles out under NDEBUG, a static helper that only a test calls. [[maybe_unused]] records the intent:

mu.cc
#include <assert.h>
#include <stdio.h>

static int handler([[maybe_unused]] int signum, int value)
{
    return value * 2;
}

int main(void)
{
    [[maybe_unused]] int checked = 5;
    assert(checked == 5);
    printf("%d\n", handler(2, 21));
    return 0;
}
Text
42

With -Wall -Wextra -DNDEBUG, the assert disappears, and checked would be reported as set but unused without the attribute. The attribute applies to variables, parameters, functions, types, enumerators and labels. It is the standard replacement for the GNU __attribute__((unused)) and the (void)param; idiom, both of which still work.

Note the position. In a parameter, the attribute goes before the type. Putting it after the declarator name is also valid in C++ but reads less clearly, and mixing the two styles in one code base invites mistakes.

deprecated: retire an API gently

[[deprecated]] marks an entity that callers should stop using. An optional string message explains the replacement:

dep.cc
[[deprecated("use parse_v2() instead")]]
int parse(const char *s);

int parse_v2(const char *s);

int run(const char *s)
{
    return parse(s);
}
Text
dep.c: In function 'run':
dep.c:8:12: warning: 'parse' is deprecated: use parse_v2() instead [-Wdeprecated-declarations]

The attribute works on functions, variables, types, enumerators and typedefs. It produces a warning, not an error, so you can ship the change and let callers migrate. When the window closes, delete the function; there is no standard way to make it an error, though GCC accepts -Werror=deprecated-declarations, which promotes the warning. For CI, enable that flag only on the part of the tree that has finished migrating.

fallthrough: mark intentional case fall-through

Falling from one case label into the next is a common source of bugs, and -Wimplicit-fallthrough, part of -Wextra, warns about it. A deliberate fall-through is marked with the attribute statement:

ft.cc
#include <stdio.h>

static void banner(int level)
{
    switch (level) {
    case 3:
        puts("high");
        [[fallthrough]];
    case 2:
        puts("medium");
        break;
    case 1:
        puts("low");
    default:
        puts("unknown");
    }
}

int main(void)
{
    banner(3);
    return 0;
}
Text
high
medium

GCC reports the fall-through from case 1 into default, which has no marker:

Text
ft.c:14:9: warning: this statement may fall through [-Wimplicit-fallthrough=]

The first fall-through, marked by [[fallthrough]];, is accepted. The attribute must be the last statement before the next label, and it must be followed by a case or default label. GCC 7 added the GNU form __attribute__((fallthrough)), and C23 and C++17 made the standard one available.

Which version do I need

Support depends on language mode and compiler release, so check your toolchain before deleting the macros. In C++, all four attributes of this post are part of C++17 (nodiscard, maybe_unused, fallthrough, with deprecated since C++14), and GCC supports them from version 7 with -std=c++17. In C, [[deprecated]], [[fallthrough]], [[maybe_unused]] and [[nodiscard]] arrived with C23, and GCC accepts the syntax with -std=c2x from GCC 10 and with the final -std=c23 spelling from GCC 14. Clang supports the C23 attributes from version 9 in -std=c2x mode. If your project builds as C11 or C17, the double-bracket syntax is accepted by GCC and Clang as an extension with a pedantic warning, which -Wno-c2x-extensions or -Wno-c23-extensions quiets.

A feature test saves guessing. __has_c_attribute(nodiscard) in C and __has_cpp_attribute(nodiscard) in C++ return a nonzero value (a date-coded number in C++) if the attribute is supported in the current mode. Combine it with a fallback macro:

compat.hc
#if defined(__has_c_attribute)
#if __has_c_attribute(nodiscard)
#define NODISCARD [[nodiscard]]
#endif
#endif
#ifndef NODISCARD
#if defined(__GNUC__)
#define NODISCARD __attribute__((warn_unused_result))
#else
#define NODISCARD
#endif
#endif

The fallback uses warn_unused_result, which has stricter semantics for the (void) cast, so tests that deliberately ignore a result need a different escape.

What the standard attributes do not give you

There is no standard always_inline, packed, aligned (C11's alignas covers one case), format, nonnull, const or pure. The C23 attributes [[unsequenced]] and [[reproducible]] come closest to const and pure, with different definitions, and support varies by compiler release, so check yours. For everything else, keep the GNU forms behind macros, or use vendor-namespaced attributes: [[gnu::format(printf, 1, 2)]], [[gnu::packed]]. The namespaced form lets you stay on one syntax, and a compiler that does not know the gnu namespace ignores it.

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.