C++ GCC – How to Disable ‘May Be Used Uninitialized’ Warning for a Variable

c++compiler-warningsgcc

I'm getting this warning on a stack variable:

warning: object.member may be used uninitialized in this function

In this case I do not wish to force initialization to just to get rid of the warning as it consumes CPU cycles. The variable is a POD structure so a memset on it is not zero cost. I can verify that the variable is never used uninitialized, so I'd just like to suppress the warning for it.

In general I do want the warning, just not on this particular variable in this particular scenario. How can I suppress the warning?


Looks like the pragma diagnostics are the correct way to go but they require quite a recent version of GCC (4.6)

No acceptable solution prior that version is known.

Best Answer

The accepted answer has two big problems that requires more than a comment. First, it deactivates the warning for the whole file. If that pragma resides in a header, probably for more. Warnings are useful and if it is indeed a false positive, one should disable the warning for a bunch of code as small as possible.

Then the warning in the OP is "maybe uninitialized" which is deactivated by -Wmaybe-uninitialized, as opposed to -Wuninitialized.

#pragma GCC diagnostic push                             // save the actual diag context
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"  // disable maybe warnings
function() or int variable;                             // impacted section of code
#pragma GCC diagnostic pop                              // restore previous diag context