liveBook · Manning

Nodiscard attribute

As explained in Modern C, Third Edition

The nodiscard attribute is a C23 attribute that recommends issuing a diagnostic when a function return value is ignored.

The C23 [[nodiscard]] attribute marks a function whose return value should not be ignored. Ignoring that value prompts a compiler diagnostic, optionally accompanied by a message. section 13.1.1 section 10.2.3

Preserving a replacement pointer

A resizable circular buffer uses [[nodiscard("returned pointer replaces function argument")]] on circular_resize. Because resizing may replace the allocation, callers must use the returned pointer rather than assume the original argument remains valid: circular* circ = circular_resize(circ, new_length); Discarding the result produces the warning that the attribute is intended to prevent. section 13.1.1

TAKEAWAY

 [[nodiscard("returned pointer replaces function argument")]]
 [[deprecated("implementation")]]
 circular* circular_resize(circular* c, size_t nlen) {
   if (c) {
     size_t len = c->len;
     if (len > nlen) return nullptr;
     size_t olen = c->cap;
     if (nlen != olen) {
       size_t ostart = circular_getpos(c, 0);
       size_t nstart = ostart;
       double* otab = c->tab;
       double* ntab;
       if (nlen > olen) {

Inspect the annotated circular_resize declaration to see [[nodiscard]] paired with a message explaining that the returned pointer replaces the argument. section 13.1.1

How Modern C, Third Edition covers it

How deep it goes
Defines syntax, optional messages, and warning behavior, then demonstrates pointer replacement without detailing diagnostic rules further.
Examples
Demonstrates [[nodiscard]] on circular_new and circular_resize, including a message for a replacement pointer.
What you can do after
Apply it via C23 attribute syntax to expose ignored results that may invalidate resource or pointer state.
How it connects
Connects [[nodiscard]] with C23 attributes, compiler diagnostics, function return values, and pointer replacement.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.