Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) auto

 

auto is a keyword that has different meanings, depending on the standard used:

 

 

 

 

 

C++98 auto in the C++98 standard

 

auto as described in the ISO/IEC 14882:2003 C++ Standard is a keyword to specify that a locally declared variable is destroyed at the end of its scope. In other words: to specify to do, what already will be done. Never write auto [1].

 

int main()
{
  auto int x = 3; //Never write auto [1]
}

 

Note that when using the Qt Creator IDE, the above code already results in the compile warning 'auto' will change meaning in C++0x; please remove it.

 

 

 

 

 

C++0x auto in the C++0x standard

 

 

In the C++0x Standard, auto is useful to let the compiler determine a variable's data type In the example below, 'i' is inferred to be of type std::vector<int>::const_iterator.

 

#include <iostream>
#include <vector>

int main()
{
  std::vector<int> v;
  v.push_back(1);
  v.push_back(2);
  v.push_back(3);

  //auto determines the type
  const auto j = v.end();
  for (auto i = v.begin(); i!=j; ++i)
  {
    std::cout << *i << '\n';
  }
}

 

Technical note: the code shown is compiled successfully using the G++ 4.4.5 compiler, which is supplied with the Qt Creator 2.0.0 IDE.

 

 

 

 

 

Qt Creator Note for Qt Creator users

 

Add the following line to your Qt project file to work with C++0x:

 

QMAKE_CXXFLAGS += -std=c++0x

 

 

 

 

 

References

 

  1. Herb Sutter. Exceptional C++ style. 2005. ISBN: 0-201-76042-8. Item 28 guideline: 'Never write auto'.

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict