Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

g++ does not show a 'unused' warning

Tags:

c++

g++

I have a little piece of code in C++:

#include <iostream> #include <iterator> #include <string>  using namespace std;  int main() {      int i=0;     istream_iterator<string> EOS;     double x;      return 0; } 

Now i compile it with my g++ (GCC) 4.4.4

g++ -W -Wall -pedantic test.cc -o test 

And get:

test.cc: In function 'int main()': test.cc:9: warning: unused variable 'i' test.cc:11: warning: unused variable 'x' 

Why there is no warning for unused EOS?

like image 231
Kylo Avatar asked Mar 14 '11 18:03

Kylo


People also ask

How do I get rid of the unused variable warning?

Solution: If variable <variable_name> or function <function_name> is not used, it can be removed. If it is only used sometimes, you can use __attribute__((unused)) . This attribute suppresses these warnings.

What is unused parameter in C?

In GCC, you can label the parameter with the unused attribute. This attribute, attached to a variable, means that the variable is meant to be possibly unused. GCC will not produce a warning for this variable.


2 Answers

It is not a primitive value, so its constructor and/or destructor might have desired side effects.

To illustrate that this happens in practice: I use a class to time sections of code, that looks roughly like this:

class Timed {     double start;     public:         Timed() { start = now(); }         ~Timed() { std::cout << (now() - start) << '\n'; } } 

So to measure how long a function takes, I simply do:

void slow() {     Timed t;     // heavy operation here... } 

The variable t never gets used, but it's still important to the behaviour of the code.

like image 122
Thomas Avatar answered Sep 21 '22 18:09

Thomas


istream_iterator<string> has a constructor, so the declaration of EOS isn't really a no-op like the declarations of i and x are.

Often you want to declare a class-type object and then not do anything with it. For example, consider std::lock_guard in C++0x (boost::scoped_lock in Boost) or any other kind of scope guard class. You don't usually want to do anything with that kind of object, you just want to create the object so that its destructor get run at the end of the block to perform whatever cleanup needs to be performed.

like image 43
James McNellis Avatar answered Sep 22 '22 18:09

James McNellis