Domanda

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.

È stato utile?

Soluzione

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".

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top