Quantcast
Channel: candrews.net » C++
Viewing all articles
Browse latest Browse all 5

Understanding C++ 0x: The ‘auto’ keyword

$
0
0

There are few phrases that cause stoic C++ programmers to weep like “iterator loop”. Your run-of-the-mill iterator loop looks like this:

for(std::vector<std::wstring>::iterator it = fruits.begin();
    it != fruits.end();
    ++it)
{
   // The carpal tunnel hurts so badly
   std::cout << (*it) << std::endl;
}


God save your soul if you have a 2 dimensional array using vectors to loop through. Needless to say, “pretty” is not the adjective most would use to describe this code. Oh, if only there were some type of new language construct that could solve this problem, you say! Well today is your lucky day, my friend. Enter the ‘auto’ keyword!

for(auto it = fruits.begin(); it != fruits.end(); ++it)
{
   // Ahhh, that's better
   std::cout << (*it) << std::endl;
}

The way that the auto keyword works is that it fills in types that are easily inferable. What does that mean? Well, let’s see.

// Things that will work
// auto = int
auto a = 1;
// auto = double
auto b = 3.14159;
// auto = vector<wstring>::iterator
vector<wstring> myStrings;
auto c = myStrings.begin();
// auto = vector<vector<char> >::iterator
vector<vector<char> > myCharacterGrid;
auto d = myCharacterGrid.begin();
// auto = (int *)
auto e = new int[5];
// auto = double
auto f = floor(b);
// auto = float
auto g = myFunctionThatReturnsAFloat();

// Things that WON'T work
// You must immediately assign a value into the 'auto' variable (same line)
auto h;
// You can't list 'auto' as a type during a class/struct/function declaration
struct MyStruct
{
   // The compiler is not fueled by unicorns
   auto myDataMember;
}
void MyFunction(auto xyz);
// You can't have different data type declarations on the same line
auto i = 1, j = 2.0, k = 'k';

The examples go on, but by this point you should certainly see a trend – if there’s some way that the compiler can deduce the data type for auto, it will, but don’t expect it to work miracles.

The auto keyword is a fantastic feature of C++ 0x and should help you stave off the carpal tunnel syndrom for at least a few more of those late night coding sessions.


Viewing all articles
Browse latest Browse all 5

Trending Articles