I'd like to see all the places in my code (C++) which disregard return value of a function. How can I do it - with gcc or static code analysis tool?
Bad code example:
int f(int z) {
return z + (z*2) + z/3 + z*z + 23;
}
int main()
{
int i = 7;
f(i); ///// <<----- here I disregard the return value
return 1;
}
Please note that:
- it should work even if the function and its use are in different files
- free static check tool
The classic 'lint' program used to be very voluble about functions that returned a value that was ignored. The trouble was, many of those warnings were unwanted - leading to excessive noise in the lint output (it was picking up bits of fluff that you wanted it to ignore). That's probably why GCC doesn't have a standard warning for it.
The other issue - the flip side - is "how do you suppress the warning when you know you are ignoring the result but really don't care". The classic scenario for that is:
You care about the first result from
signal()
; you know that the second will be SIG_IGN (since you just set it to that). To get away from the warnings, I sometimes use some variant on:This assigns to
old
both times. You can follow that with 'assert(old == SIG_IGN)'.a static analyzer will do the work for you, but if your code base is more then trivial prepare to be overwhelmed ;-)
A static analyzer will be your best bet here. We use Coverity here, but there are free tools available that you can use as well.
If you need a quick-and-dirty solution and you have a Linux-style shell handy, you can try something like:
That will find every line that references the specified function but does not contain an "=". You can get a lot of false positives (and potentially some false negatives) but if you don't have a static analyzer it's a decent place to start.
For C++17 the answer to this question changes since we now have the [[nodiscard]] attribute. Covered in [dcl.attr.nodiscard]:
and
So modifying your example (see it live):
We now obtain a diagnostic with both gcc and clang e.g.
As far as I'm aware there is no GCC option to give this warning. However, if you are interested in specific functions, you can tag them with an attribute:
which would give a warning if the return value of fn() was not used. Caveat: I've never used this feature myself.
You want GCC's
warn_unused_result
attribute:Trying to compile this code produces:
You can see this in use in the Linux kernel; they have a
__must_check
macro that does the same thing; looks like you need GCC 3.4 or greater for this to work. Then you will find that macro used in kernel header files: