MSVC equivalent __attribute__ ((warn_unused_result))?

I find __attribute__ ((warn_unused_result)) very useful as a means of encouraging developers not to ignore the error codes returned by functions, but I need this to work with MSVC as well as with gcc and gcc-compatible compilers such as ICC. Do Microsoft Visual Studio C / C ++ compilers have an equivalent mechanism? (I tried wading through MSDN without any luck.)

+19
c ++ c gcc visual-c ++ gcc-warning
Nov 19 '10 at 15:12
source share
4 answers

This is _Check_return_ . See here for examples of similar annotations and here for function behavior. It has been supported since MSVC 2012.

Example:

 _Check_return_ int my_return_must_be_checked() { return 42; } 
+9
Mar 31 '14 at 7:12
source share

UPDATE FOR MSVC 2012 AND AFTER

Many thanks to @Albert for pointing out that MSVC now supports _Check_return_ annotation compared to Visual Studio 2012 when using static SAL code analysis. I am adding this answer to include a cross-platform macro that 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 and others, (a) MSVC requires annotations for both the declaration and the definition of the function, and (b) the annotation should be at the beginning of the declaration / definition (gcc allows either). Therefore, the use should usually be, for example:


 // foo.h CHECK_RETURN int my_function(void); // declaration 


 // foo.c CHECK_RETURN int my_function(void) // definition { return 42; } 


Also note that to compile from the command line you will need /analyze (or -analyze ), or the equivalent if you are using the Visual Studio IDE. It also slows down the build process.

+8
Mar 31 '14 at 10:33
source share

Some editions of VisualStudio come with a static analysis tool, formerly called PREFast (now simply called "Code Analysis for C / C ++"). PREFast uses annotations to mark up code. One of these annotations, MustCheck , does what you are looking for.

+5
Nov 19 '10 at 15:34
source share

As far as I know, MS compilers do not have an equivalent pragma or attribute - the only "unused" warning you can get is a variable when you turn on the optimizer with the appropriate warning level.

+3
Nov 19 '10 at 15:21
source share



All Articles