Disable GCC “may be used uninitialized” on a particular variable

拈花ヽ惹草 提交于 2019-12-02 17:59:19

Try doing this:

 #pragma GCC diagnostic ignored "-Wuninitialized"
        foo(b);         /* no diagnostic for this one */

This pragma comes in three interesting and helpful flavors : warning, error, ignored. See 6.56.10 Diagnostic Pragmas for their usages. The link says,

GCC allows the user to selectively enable or disable certain types of diagnostics, and change the kind of the diagnostic. For example, a project's policy might require that all sources compile with -Werror but certain files might have exceptions allowing specific types of warnings. Or, a project might selectively enable diagnostics and treat them as errors depending on which preprocessor macros are defined.

@Nawaz has answered the question as specifically asked, but have you considered that the fact that you need this may indicate you're declaring your struct too early/at a less nested scope than appropriate? It would generally be much preferred if you could declare your struct at a point where you can actually initialize it rather than declaring it earlier and filling it in various locations.

Also, even though you can verify that it's never used uninitialized right now, what if someone else adds a new code path in the future and it's not initialized properly? If you disable the warning then it'll silently compile and probably break in an unexpected way. Unless you can prove that the initialization is taking a measurable amount of your program's CPU it's probably better to just do the initialization up front.

GCC differentiates between uninitalised and self initalized, e.g. compiling:

int main() {
   int i = i;
   return i;
}

With gcc -Wall -Wextra gives no warnings, unless you explicitly added -Winit-self as well, yet it gets completely optimized out by my quick testing.

The accepted answer has two big problem 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 usefuls 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 deactived by -Wmaybe-uninitialized, as opposed to -Wuninitialized.

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
function() or int variable;
#pragma GCC diagnostic pop
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!