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
- Attach [[nodiscard]] when silently discarding a function result risks incorrect use. section 13.1.1
- Add a string argument when the diagnostic should explain why the result matters. section 13.1.1 section 10.2.3
[[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
