C++ attribute specifiers

C++ attribute specifiers add metadata to declarations and definitions. The metadata can be used by the compiler and by the developer to help understand the code intent.

Commonly used C++17 attributes such as [[maybe_unused]] and [[fallthrough]] suppress compiler warnings and signal developer intent for clarity.

C++20 attributes such as [[likely]] and [[unlikely]] may be used by the compiler to optimize compilation, and also provide human code readers insight into the intent of the algorithm.

GCC ≥ 5 feature test macro __has_cpp_attribute() checks if an attribute is supported by the compiler–even if the command line specified standard is older.

maybe_unused attribute

To enable code to fallback to no attribute with older compilers, use [[maybe_unused]] attribute in declaration AND in the definition to be compatible with GCC:

int windows_fun(int x, [[maybe_unused]] int y) {

#ifdef _WIN32
  return y;
#else
  return x;
#endif
}

On non-Windows systems, the compiler would have issued a warning about y being an unused argument. The [[maybe_unused]] attribute suppresses that warning.

fallthrough attribute

The [[fallthrough]] attribute is used to indicate that a fall-through in a switch statement is intentional. This attribute can be used to suppress warnings about missing break statements in a switch block.

In the header file:

#ifndef __has_cpp_attribute
#define __has_cpp_attribute(x) 0
#endif

#if __has_cpp_attribute(likely)
#define LIKELY [[likely]]
#else
#define LIKELY
#endif

switch (x) {
  case 1:
    x++;
    [[fallthrough]];
  case 2:  LIKELY
    x--;
}