I'm finding __attribute__ ((warn_unused_result))
to be very useful as a means of encouraging developers not to ignore error codes returned by functions, but I need this to work with MSVC as well as gcc and gcc-compatible compilers such as ICC. Do the Microsoft Visual Studio C/C++ compilers have an equivalent mechanism ? (I've tried wading through MSDN without any luck so far.)
It's _Check_return_
. See here for examples of similar annotations and here for function behaviour. It's supported since MSVC 2012.
Example:
_Check_return_
int my_return_must_be_checked() {
return 42;
}
Many thanks to @Albert for pointing out that MSVC now supports the annotation _Check_return_
as of Visual Studio 2012 when using SAL static code analysis. I'm adding this answer so that I can include a cross-platform macro which may be useful to others:
#if defined(__GNUC__) && (__GNUC__ >= 4)
#define CHECK_RESULT __attribute__ ((warn_unused_result))
#elif defined(_MSC_VER) && (_MSC_VER >= 1700)
#define CHECK_RESULT _Check_return_
#else
#define CHECK_RESULT
#endif
Note that, unlike gcc et al, (a) MSVC requires annotations on both declaration and definition of a function, and (b) the annotation needs to be at the start of the declaration/definition (gcc allows either). So usage will typically need to be e.g.:
// foo.h
CHECK_RETURN int my_function(void); // declaration
// foo.c
CHECK_RETURN int my_function(void) // definition
{
return 42;
}
Note also that you'll need the /analyze
(or -analyze
) switch if compiling from the command line, or the equivalent if using the Visual Studio IDE. This also tends to slow the build down somewhat.
Some editions of VisualStudio come packaged with a static analysis tool that used to be called PREFast (Now called simply "Code Analysis for C/C++"). PREFast uses annotations to mark up code. One of those annotations, MustCheck, does what you're looking for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With