[Issue 3882] New: Unused result of pure functions

d-bugmail at puremagic.com d-bugmail at puremagic.com
Fri Mar 5 10:31:15 PST 2010


http://d.puremagic.com/issues/show_bug.cgi?id=3882

           Summary: Unused result of pure functions
           Product: D
           Version: 2.040
          Platform: All
        OS/Version: All
            Status: NEW
          Severity: enhancement
          Priority: P2
         Component: DMD
        AssignedTo: nobody at puremagic.com
        ReportedBy: bearophile_hugs at eml.cc


--- Comment #0 from bearophile_hugs at eml.cc 2010-03-05 10:31:12 PST ---
The following small program:

void main() {
    int x = 5;
    x + 3;
}

Currently produces the compile error:
Error: + has no effect in expression (x + 3)
because that's often a small bug in the program.

Equally, a pure function has no side effects, so its only purpose is to return
a value. So the compiler can issue a warning or error if its return value is
not used. This can help avoid some small bugs.

This predecessor() function computes the predecessor of its input argument, its
result is always nonnegative:


pure int predecessor(int x) {
    if (x <= 0)
        throw new Exception("");
    return x - 1;
}
void main() {
    predecessor(5); // warning or error
}


In theory a pure function can be used just for the exceptions it throws, but I
think this is a quite uncommon usage.

A "pure nothrow" function can't even have this uncommon purpose, so this can
produce a compile error:

pure nothrow int predecessor(int x) {
    return x - 1;
}
void main() {
    predecessor(5); // error
}

--------------

In GCC there is a function attribute named "warn_unused_result":
http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html

The warn_unused_result attribute causes a warning to be emitted if a caller of
the function with this attribute does not use its return value. This is useful
for functions where not checking the result is either a security problem or
always a bug, such as realloc.

Similar attribute can be named like @do_use_result in D2.

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list