0

One common error in C++ is forgetting to look at the return value of a function. something like that:

void func() {
    SetEvent(some_handle);
}

Is there a way (using some static analyzer maybe?) to find all of these occurrences?

I want to force my code to either look at the result of all non-void functions, or explicitly ignore it like that:

void func() {
    (void)SetEvent(some_handle);
}

Something like defining all of the functions as [[nodiscard]] or as x__warn_unused_result__.

I'm using VS, but a good static-analyzer is good too.

user972014
  • 3,296
  • 6
  • 49
  • 89
  • Throw an exception. That forces the caller (or, at minimum, some function in the call stack) to catch the exception, as the program will terminate otherwise. – Peter Oct 28 '16 at 11:55
  • 3
    @Peter Throwing an exception from the function only to make sure the caller doesn't discard the value? That sounds fishy. – Hatted Rooster Oct 28 '16 at 11:56
  • 1
    OP, take a look at http://stackoverflow.com/questions/2042780/how-to-raise-warning-if-return-value-is-disregarded-gcc-or-static-code-check, specifically http://stackoverflow.com/a/2043261/1870760 and http://stackoverflow.com/a/2042785/1870760 – Hatted Rooster Oct 28 '16 at 11:57
  • @Bill Gates - expecting to force the caller to check the return value from a function is also fishy. – Peter Oct 28 '16 at 11:57
  • From C++17, there is attribute `nodiscard`, see [attribute](http://en.cppreference.com/w/cpp/language/attributes) – Danh Oct 28 '16 at 12:08
  • If you are using gcc, there is an option for it `-Wunused-result` – Danh Oct 28 '16 at 12:11
  • @Danh - the attribute `nodiscard` is a suggestion to the compiler to issue a warning. I would not necessarily describe that as forcing use of the return value (unless the compiler does actually issue a warning, and is configured to treat warnings as compilation errors). Same for gcc's `-Wunused-result`. – Peter Oct 28 '16 at 12:35

0 Answers0