Home Ask Login Register

Developers Planet

Your answer is one click away!

Al Bundy February 2016

gcc does not warn "variable set but not used"

I have this MCVE which compiles without any warning:

auto foo() -> void
    int unused = 0;

For me I would expect error: variable ‘unused’ set but not used [-Werror=unused-but-set-variable].

This MCVE compiles also without any warning:

auto foo() -> void
    int x;
    int unused;
    for ( ; x < 100; x++ )  unused++;

Here I would expect these two errors:

  1. error: variable ‘unused’ set but not used [-Werror=unused-but-set-variable].
  2. error: ‘unused’ and ‘x’ are used uninitialized [-Werror=uninitialized]

Adding bar( unused ); above the for loop forces gcc to display the warning regarding using uninitialized variable.

Why is gcc 4.9.3 not complaining in any of both MCVE's?

Compile command: g++ -O3 -c -Wall -Wextra -Werror -std=c++11 foo.cpp

Compiling it with -O1 I get this warning for the line with for : error: ‘x’ may be used uninitialized in this function [-Wmaybe-uninitialized]. All other optimization levels do not produce any warning.


ul90 February 2016

The variables are not unused for the compiler. This warning is triggered only if you declare a local variable (and eventually initialize it) but then never use this variable in any statement.

So, in your examples, the variable unused is declared, initialized (in the first example) and used in the 2nd statement (here for reading and writing). The variable x is also declared and used (but not initialized).

In your second example, the compiler should show an "uninitialized" warning for the variable x. It may be an compiler bug if this warning is shown for -O1 only?

Al Bundy February 2016

It is a 5 1/2 years old bug.

See GCC Bugzilla – Bug 44677

Post Status

Asked in February 2016
Viewed 1,195 times
Voted 9
Answered 2 times


Leave an answer

Quote of the day: live life