Andrej Mitrovic: > I think what might help out in D is if we had a way to mark some > functions so the compiler guarantees that their return values *are > not* to be discarded. For example, this code will compile: > > import std.stdio; > import std.string; > void main() > { > string s = "Mary has a lil lamb."; > replace(s, "lil", "li'l"); // returns a copy, but discards it > } > > If the replace function is marked with some kind of @nodiscard > annotation, then his would be a compile error since it doesn't make > sense to construct a new string, return it, and discard it. > > But maybe that's going overboard. How often do these kinds of bugs creep in?
Such bugs are common enough. GNU C has the warn_unused_result attribute (that is like your @nodiscard if you use -Werror to turn warnings into errors): http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html Some C lints require a void cast where you don't want to use a function result: cast(void)replace(s, "lil", "li'l"); In a language the default is different and where you don't want to use a function result you have to add an annotation: unused replace(s, "lil", "li'l"); Something like @nodiscard is more useful in C than D because in C there are no true built-in exceptions, so error return values are common, and ignoring them is a mistake. In some cases like replace() or the C realloc() ignoring a result is always a programmer error. So something like @nodiscard is useful in D too. Bye, bearophile