Using attributes in C++

A useful way to communicate with the compiler and other developers through code

CMP
3 min readJan 16, 2024

All (good) programmers know that adding comments to code is important for maintainability and clarity. Commenting code can help express certain intentions of the code to future developers without speaking to them directly, such as if a function is expected to be deprecated soon or to explain a complex algorithm.

Sometimes, it’s not other developers who get confused by code — it’s the compiler! In some cases, programmers can add compiler flags when building code or #pragma directives in the code to help suppress compiler warnings, but this is not always ideal.

Fortunately, beginning in C++11 and continuing in C++14, C++17, and beyond, attributes have been added to the language as a way to provide additional information about the code to tell the compiler and developers about expected behavior.

Attribute specifier syntax

The basic syntax for specifying an attribute is to use double square brackets, such as [[attribute]]. To specify multiple attributes, either provide a comma-separated list within double brackets, or multiple double-bracket attributes. For example:

[[attribute1]] [[attribute2]] [[attribute3]]
int myFunc();

// OR

[[attribute1, attribute2, attribute3]]
int myFunc();

The placement of an attribute determines which entity will have the attribute applied to. Examine the…

--

--

CMP

Software engineer specializing in operating systems, navigating the intracicies of the C++ language and systems programming.