0

Whenever I compile my code I observe following two warnings:

warning: '<variable>' defined but not used
warning: unused variable '<variable>'

I tried to google but I did not find any helpful thread or blog about what is the difference between these two warnings.

Example with some sample code snippet will do for me or if am duplicating some existing thread please feel free to refer.

gmuhammad
  • 1,434
  • 4
  • 25
  • 39

1 Answers1

1

I think the difference is kind of subtle but here is the code snippet along with the compiler output that demonstrates some differences:

#include <iostream>

static const char * hello = "Hello";

void foo() {
    int i;
     std::cout << "foo" << std::endl;
}
...
argenet@Martell ~ % g++ /tmp/def_not_used.cpp -Wall
/tmp/def_not_used.cpp: In function ‘void foo()’:
/tmp/def_not_used.cpp:6:9: warning: unused variable ‘i’ [-Wunused-variable]
     int i;
         ^
/tmp/def_not_used.cpp: At global scope:
/tmp/def_not_used.cpp:3:21: warning: ‘hello’ defined but not used [-Wunused-variable]
 static const char * hello = "Hello";

So here the local variable is never used, therefore the compiler may simply omit it while generating the code and it emits an "unused variable" warning.

At the same time, the static C-style literal cannot be omitted that easily as it is available for a wider scope (the whole .cpp file). However, it is not referenced by any code in this module so the compiler warns about it like "defined but not used".

francescalus
  • 30,576
  • 16
  • 61
  • 96
Argenet
  • 379
  • 2
  • 9
  • I tried your sample but I got the same warning for both variables: macbookpro-116:temp Developer$ g++ -Wall warnings.cpp -o warnings.opp warnings.cpp:7:9: warning: unused variable 'i' [-Wunused-variable] int i; ^ warnings.cpp:4:21: warning: unused variable 'hello' [-Wunused-variable] static const char * hello = "Hello"; ^ 2 warnings generated. – gmuhammad Mar 24 '14 at 07:49
  • 1
    @gmuhammad just in case - I'm using GCC 4.8.2 at Linux. From your cli prompt I guess you're running GCC on Mac, perhaps the version/platform difference matters somehow, although I'd expect them to behave identically.. – Argenet Mar 24 '14 at 07:51
  • Yup! you are right. I tried the code on CentOS and it gave me two different warnings, just like you described in your answer. Thank you. But is there any way to suppress only "defined but not used" ? I mean "unused variable" is desirable for me but I want "defined but not used" to be suppressed. – gmuhammad Mar 24 '14 at 10:42
  • 1
    From what I see they both are shown due to the same command-line flag [-Wunused-variable] thus I doubt it is possible to supress only one of them, moreover that they're pretty close in their meaning. But doesn't this warning mean that there are some variables/objects which are of no need and you could simply remove it? – Argenet Mar 24 '14 at 11:12