Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A variable not detected as not used

I am using g++ 4.3.0 to compile this example :

#include <vector>

int main()
{
  std::vector< int > a;
  int b;
}

If I compile the example with maximum warning level, I get a warning that the variable b is not used :

[vladimir@juniper data_create]$ g++ m.cpp -Wall -Wextra -ansi -pedantic
m.cpp: In function ‘int main()’:
m.cpp:7: warning: unused variable ‘b’
[vladimir@juniper data_create]$

The question is : why the variable a is not reported as not used? What parameters do I have to pass to get the warning for the variable a?

like image 479
BЈовић Avatar asked Nov 01 '10 16:11

BЈовић


People also ask

Why is my local variable not being used?

If you see "The value of the local variable string is not used" warning message in your class while using Eclipse IDE, the reason is that you have declared a local variable (a variable inside a method) and you have not used it anywhere in your class.

How do you avoid declared but not used?

To avoid this error – Use a blank identifier (_) before the package name os. In the above code, two variables name and age are declared but age was not used, Thus, the following error will return. To avoid this error – Assign the variable to a blank identifier (_).


2 Answers

In theory, the default constructor for std::vector<int> could have arbitrary side effects, so the compiler cannot figure out whether removing the definition of a would change the semantics of the program. You only get those warning for built-in types.

A better example is a lock:

{
    lock a;
    // ...
    // do critical stuff
    // a is never used here
    // ...
    // lock is automatically released by a's destructor (RAII)
}

Even though a is never used after its definition, removing the first line would be wrong.

like image 121
fredoverflow Avatar answered Oct 16 '22 21:10

fredoverflow


a is not a built-in type. You are actually calling the constructor of std::vector<int> and assigning the result to a. The compiler sees this as usage because the constructor could have side effects.

like image 31
jilles de wit Avatar answered Oct 16 '22 21:10

jilles de wit