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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With