handmade.network » Forums » Compiler warning for not accepting function return value?
boagz57
Jason
55 posts
#16756 Compiler warning for not accepting function return value?
1 month ago Edited by Jason on Nov. 12, 2018, 9:46 p.m.

Hey all,

So my current codebase contains both functions that have normal return values as well as out parameters. However, I recently had a difficult to find bug because I treated a function with a return value as an out parameter function and so I never stored the return value. I also find it difficult to know, just by looking at some code, which function parameters are being modified within a function and which aren't. So I want to convert things so that most if not all of functions return a value (or values with C++17 structured bindings) instead of having out parameters. While I'm making the transition however, I was wondering if there was a compiler warning that I can set to specifically check to see if a function's return value was captured or not, since old habits die hard lol. If not, then what are you preferred methods for dealing with the described issues above (if you had issues like I do now)?
ratchetfreak
419 posts
#16757 Compiler warning for not accepting function return value?
1 month ago

the annotation would be called something like nodiscard.

in C++17 it's become a standard annotation: [[nodiscard]]

1
2
3
4
5
[[nodiscard]] Foo dont_discard_me_bro(){
    Foo result;
    result = ...;
    return result;
}
mmozeiko
Mārtiņš Možeiko
1832 posts / 1 project
#16758 Compiler warning for not accepting function return value?
1 month ago Edited by Mārtiņš Možeiko on Nov. 12, 2018, 10:13 p.m.

In pre-C++17, works also with C:
1
2
3
4
5
6
7
8
9
#ifdef _MSC_VER
// compile with "/analyze" cl.exe option
#include <sal.h>
#define WARN_UNUSED _Check_return_
#else
#define WARN_UNUSED __attribute__((warn_unused_result))
#endif

WARN_UNUSED int f() { ... }

boagz57
Jason
55 posts
#16763 Compiler warning for not accepting function return value?
1 month ago

Awesome. Thanks guys.