Suppress unused variable warning in C++ => Compiler bug or code bug?

WilliamKF picture WilliamKF · Dec 15, 2009 · Viewed 16.1k times · Source

Presently, I am using the following function template to suppress unused variable warnings:

template<typename T>
void
unused(T const &) {
  /* Do nothing. */
}

However, when porting to cygwin from Linux, I am now getting compiler errors on g++ 3.4.4 (On linux I am 3.4.6, so maybe this is a bug fix?):

Write.cpp: In member function `void* Write::initReadWrite()':
Write.cpp:516: error: invalid initialization of reference of type 'const volatile bool&' from expression of type 'volatile bool'
../../src/common/Assert.h:27: error: in passing argument 1 of `void unused(const T&) [with T = volatile bool]'
make[1]: *** [ARCH.cygwin/release/Write.o] Error 1

The argument to unused is a member variable declared as:

  volatile bool readWriteActivated;

Is this a compiler bug or a bug in my code?

Here is the minimal test case:

template<typename T>
void unused(T const &) { }

int main() {
  volatile bool x = false;
  unused(!x); // type of "!x" is bool
}

Answer

haavee picture haavee · Dec 15, 2009

The actual way of indicating you don't actually use a parameter is not giving it a name:

int f(int a, float) {
     return a*2;
}

will compile everywhere with all warnings turned on, without warning about the unused float. Even if the argument does have a name in the prototype (e.g. int f(int a, float f);), it still won't complain.