### 6.7 Optimization and compiler warnings ¶

When optimization is turned on, GCC can produce additional warnings that do not appear when compiling without optimization.

As part of the optimization process, the compiler examines the use of all variables and their initial values—this is referred to as data-flow analysis. It forms the basis for other optimization strategies, such as instruction scheduling. A side-effect of data-flow analysis is that the compiler can detect the use of uninitialized variables.

The `-Wuninitialized` option (which is included in `-Wall`) warns about variables that are read without being initialized. It only works when the program is compiled with optimization, so that data-flow analysis is enabled. The following function contains an example of such a variable:

    int
    sign (int x)
    {
      int s;

      if (x > 0)
        s = 1;
      else if (x < 0)
        s = -1;

      return s;
    }

The function works correctly for most arguments, but has a bug when `x` is zero—in this case the return value of the variable `s` will be undefined.

Compiling the program with the `-Wall` option alone does not produce any warnings, because data-flow analysis is not carried out without optimization:

    $ gcc -Wall -c uninit.c

To produce a warning, the program must be compiled with `-Wall` and optimization simultaneously. In practice, the optimization level `-O2` is needed to give good warnings:

    $ gcc -Wall -O2 -c uninit.c
    uninit.c: In function `sign':
    uninit.c:4: warning: `s' might be used uninitialized
      in this function

This correctly detects the possibility of the variable `s` being used without being defined.

Note that while GCC will usually find most uninitialized variables, it does so using heuristics which will occasionally miss some complicated cases or falsely warn about others. In the latter situation, it is often possible to rewrite the relevant lines in a simpler way that removes the warning and improves the readability of the source code.