cpp17 · medium
C++17: [[nodiscard]], [[maybe_unused]], [[fallthrough]]
C++17 standardized three widely useful attributes. [[nodiscard]], applied to a function or a type, makes the compiler warn when the return value is discarded — invaluable for error codes, allocations, and RAII handle/guard results; C++20 adds an explanatory string, [[nodiscard("reason")]]. [[maybe_unused]] suppresses unused-entity warnings for variables, parameters, functions, types, or enumerators that are used only in some build configurations — the textbook case being a variable referenced only inside assert(), which disappears under NDEBUG; it documents intent more clearly than the old (void)x; cast. [[fallthrough]], placed as the last statement of a switch case before the next label, declares that an implicit fall-through is deliberate and silences the implicit-fallthrough warning while documenting the intent for readers. Related standard attributes include [[deprecated]] and the C++20 [[likely]]/[[unlikely]] branch hints.
C++17 standard attributes: [[nodiscard]] warns when a return value is ignored (error codes, handles); [[maybe_unused]] silences unused-warnings for assert-only/interface entities; [[fallthrough]] marks a deliberate switch fall-through.
The code
[[nodiscard]] int compute(); // warn if the result is ignoredcompute(); // WARNING: discarded value
void f([[maybe_unused]] int debugOnly) { // no 'unused param' warning [[maybe_unused]] int x = check(); // used only in assert()}
switch (n) {case 1: setup(); [[fallthrough]]; // 'I meant to fall through'case 2: run(); break;}What this lesson walks through
- 01[[nodiscard]] — do not ignore this result
- 02[[maybe_unused]] — intentionally unused
- 03Gotcha — they only advise the compiler
- 04[[fallthrough]] — deliberate switch fall-through
[[nodiscard]] on a function (or on a type) makes the compiler warn when the return value is discarded. It is for results that are dangerous to drop: error codes, allocations, RAII handles/guards, and any 'pure' query whose only purpose is its return value. C++20 lets you add a reason string: [[nodiscard("check the error")]].
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of C++17: [[nodiscard]], [[maybe_unused]], [[fallthrough]] and 100+ animated C++ interview lessons.