D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 5464 - Attribute to not ignore function result
Summary: Attribute to not ignore function result
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P2 enhancement
Assignee: No Owner
URL:
Keywords: bootcamp, pull
: 20165 (view as issue list)
Depends on:
Blocks:
 
Reported: 2011-01-20 02:59 UTC by bearophile_hugs
Modified: 2022-08-15 14:04 UTC (History)
3 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description bearophile_hugs 2011-01-20 02:59:14 UTC
Ignoring the result of some functions like string replace(), or the C realloc(), or in general the result of strongly pure functions in D, is a programmer mistake that often enough is a sign of a bug presence.

To face this problem GNU C has the warn_unused_result attribute:
http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
(This is more useful in C than D because in C there are no true built-in exceptions, so error return values are common, and sometimes ignoring them is a mistake.)

Some C lints require a void cast where you don't want to use a function result:
cast(void)foo(x);

In a language the default is different and where you don't want to use a function result you have to add a specific annotation:
unused foo(x);

In D an attribute like @nodiscard (name invented by Andrej Mitrovic) may turn ignoring return values into errors. To silence this error the programmer uses something like cast(void).

So the error message may be:
"Error: unused result of @nodiscard function. Use cast(void) to override it."

Strongly pure functions may produce this error even if you don't use @nodiscard.
Comment 1 bearophile_hugs 2011-02-28 04:19:31 UTC
In Phobos there are several functions that have no important effects (despite sometimes not being pure) that are useful just for their return value, like isSorted, front, setDifference, etc. @nodiscard is useful for them all.

See also bug 3882
Comment 2 Paul Backus 2020-08-24 21:03:01 UTC
*** Issue 20165 has been marked as a duplicate of this issue. ***
Comment 3 Dlang Bot 2020-09-19 02:42:16 UTC
@pbackus created dlang/dmd pull request #11765 "[PoC] Add @nodiscard attribute" fixing this issue:

- Add @nodiscard attribute
  
  Fixes issue 5464 - Attribute to not ignore function result

https://github.com/dlang/dmd/pull/11765
Comment 4 RazvanN 2022-08-15 14:04:54 UTC
This has been addressed by the addition of @mustuse: https://github.com/dlang/dmd/pull/13589