C – GCC Compiler Ignores Uninitialized Variable Warning for Debug Build

c++gccgcc-warning

gcc compiler ignores uninitialized variable warning for debug build. This looks very weird for me, can some one help me to understand this ?

## Program  
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    int i, max;
    int count;
    if (argc < 2) {
        return -1;
    }
    max = atoi(argv[1]);
    for (i = 0; i < max; i++) {
        count++;
    }
    printf("count is %d\n", count);
    return 0;
}

gcc a.c -g -Wall -Werror

No warning

gcc a.c -O3 -Wall -Werror

a.c: In function ‘main’:
a.c:8:9: error: ‘count’ may be used uninitialized in this function [-Werror=maybe-uninitialized]
     int count;
         ^~~~~
cc1: all warnings being treated as errors

gcc version: 7.4.0

Best Answer

Though it may look weird, this behavior is documented for -Wmaybe-uninitialized gcc option:

-Wmaybe-uninitialized

For an automatic (i.e. local) variable, if there exists a path from the function entry to a use of the variable that is initialized, but there exist some other paths for which the variable is not initialized, the compiler emits a warning if it cannot prove the uninitialized paths are not executed at run time.

These warnings are only possible in optimizing compilation, because otherwise GCC does not keep track of the state of variables.

I guess the reason is that the cost of analyzing not initialized variables is too much for not optimizing compilation. That's why it is done only for optimizing one.

Related Question