The [[nodiscard]] attribute is a way of conveying our intentions to the compiler. We'll find out more in this section.

C++17 brought a few more standard attributes. By using those extra annotations, you can make your code not only readable for other developers, but also the compiler can use this knowledge.

For example, it might produce more warnings about potential mistakes.

Or the opposite: it might avoid a warning generation because it will notice a proper intention (for example with [[maybe_unused]]).

In this chapter, you’ll see how one attribute - [[nodiscard]] - can be used to provide better safety in the code.

The [[nodiscard]] attribute was mentioned in the Attributes chapter, but here’s a simple example to recall its properties.

The attribute is used to mark the return value of functions:

[[nodiscard]] int Compute();

When you call such function and don’t assign the result:

void Foo() { 

You should get the following (or a similar) warning:

warning: ignoring return value of 'int Compute()', declared with attribute nodis​card

We can go further and not just mark the return value, but a whole type:

Get hands-on with 1200+ tech skills courses.