How can I get gcc to warn me about "int i = i;" How can I get gcc to warn me about "int i = i;" c c

How can I get gcc to warn me about "int i = i;"


For GCC compiling C programs, you need to add the compiler flag -Winit-self. (You also need -Wall or -Wuninitialized, see below.) For GCC compiling C++ programs, this flag is implied by -Wall but for C it needs to specified explicitly; it is not part of -Wextra either.

For Clang, the situation is slightly more interesting. In the snippet in the OP, Clang does not produce any diagnostic. However, with the slightly different snippet supplied in the GCC manual below, a diagnostic is provided:

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

The difference is that in the above snippet, the (uninitialized) value of i is actually used. Apparently, in the original code Clang detected that the variable was useless and eliminated it as dead code before applying the diagnostic.

In Clang, the diagnostic is triggered by -Wuninitialized, which is enabled by -Wall as in GCC.


Here's an excerpt from the GCC manual:

-Winit-self (C, C++, Objective-C and Objective-C++ only)

Warn about uninitialized variables that are initialized with themselves. Note this option can only be used with the -Wuninitialized option.

For example, GCC warns about i being uninitialized in the following snippet only when -Winit-self has been specified:

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

This warning is enabled by -Wall in C++.

As the excerpt indicates, -Wuninitialized is also required. In both C and C++, -Wall implies -Wuninitialized. However, note that many uninitialized uses will not be detected unless some optimization level is also requested. (That doesn't apply to -Winit-self, as far as I know. It can be detected without optimization.)


Irritatingly, when you unmark a question as a duplicate, the previously-marked duplicates disappear. I unmarked it because none of the duplicates actually answered the question in the body; I also edited the title.

For reference, here are the original duplicates, which may be of interest:


It is basically:

int i;i = i;

in which i is an uninitialized value.


The combination of -Wall -Winit-self seems to add this diagnostic:

$ gcc -Wall      -Winit-self t.ct.c: In function ‘main’:t.c:3:10: warning: ‘i’ is used uninitialized in this function [-Wuninitialized]     long i = i;          ^