c++boost.gif (8819 bytes)

Home
Libraries
People
FAQ
More

Header boost/utility/warnings.hpp

Contents

Function template avoid_unused_variable_warning()

Function avoid_unused_variable_warning() prevents compiler warnings about unused variables for the given variable binding, either a function argument or local variable.

template <class T>
inline void avoid_unused_variable_warning(const T &) { }

A common problem C++ programmers run into while writing portable code are "unused variable warnings" from helpful compilers. Although this is a good warning to be aware of, there are some circumstances when it just gets in the way. For example when doing debugging code:

template <class C, class T>
void f(C & c, const T & v)
{
  size_t s0 = v.size(); // warns in NDEBUG mode
  c.push_back(v);
  size_t s1 = v.size(); // warns in NDEBUG mode
  assert(s0 < s1);
}

Using this function has two important benefits: it prevents the warning from occurring, and it documents the fact that the variables are intentionally not used. For example:

template <class C, class T>
void f(C & c, const T & v)
{
  size_t s0 = v.size();
  c.push_back(v);
  size_t s1 = v.size();
  boost::avoid_unused_variable_warning(s0);
  boost::avoid_unused_variable_warning(s1);
  assert(s0 < s1);
}

The known circumstances under which compilers generate this warning vary and tends not to show up for most developers. The usual situation is that as soon as your code is subjected to the extra checking that a release level build these warnings show. Below are some of the know conditions under which the warning shows for a variety of compilers.

Compiler Warning Notes
CodeWarrior 8 Warning : variable / argument 'unused_var' is not used in function "Unused Variables" or "Unused Arguments" options enabled.
GCC 3.2.3 warning: unused variable `int unused_var`  
Visual C/C++ 7.1 warning C4189: 'unused_var' : local variable is initialized but not referenced. Warnings set to Level 4.

Contributed by Rene Rivera.


Revised  14 November, 2003

Copyright Rene Rivera 2003.

Use, modification, and distribution are subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at www.boost.org/LICENSE_1_0.txt)