c++gcccompiler-warningssuppress-warningsuninitialized-constant

Tell GCC to assume an object is initialized


When compiling in GCC with -Wall, GCC will warn about using variables that might be uninitialized. However, as the programmer, I know that a variable must be initialized if control enters a certain if statement:

int foo;

/* conditional assignment of foo goes here */

if (/* complicated condition that guarantees that foo has been initialized */){
    return test(foo);
}

In the above code, GCC will complain that foo may be used uninitialized. In particular, the complain will arise from inside the definition of test(), where foo is actually used.

Is there a GCC builtin or equivalent to tell the compiler that foo is already initialized? For example:

if (/* complicated condition that guarantees that foo has been initialized */){
    __assume_initialized(foo);
    return test(foo);
}

Note that placing #pragma GCC diagnostic ignored "-Wuninitialized" before the line return test(foo) is insufficient as the uninitialized warning arises from the usage (e.g. comparison) of foo in the definition of test(), possibly in another compilation unit, where the pragma won't exist.

Neither do I want to put the pragma inside the definition of test(), because the issue is not with test(). test() should of course not be called with random garbage, and putting the pragma there might cause other mistakes to go unnoticed.

Any solutions?


Solution

  • The simplest solution is to (redundantly) initialize that variable e.g. by adding:

    int foo=0;
    

    the optimizing compiler (e.g. g++ -O2) is very likely to remove that initialization if it is unneeded. BTW, if the compiler don't optimize that in your particular case, the overhead of such an initialization is really small.

    If foo is an instance of some class you could define a no-op constructor (perhaps a private: one) and make your function friend of that class. If foo is some pointer initialize it to nullptr.

    BTW, such an explicit initialization makes your code more readable and less brittle and perhaps even more CPU cache friendly. You might add a comment explaining why and how it might be unneeded. IMHO the readability increase is enough to justify such an initialization.

    I tend to always initialize locals, leaving the compiler the opportunity to optimize away most of the useless initializations.

    Alternatively (but I don't recommend that) use a function specific pragma (as mentioned in your question) to disable such a warning.