C++11 Auto Keyword

This is just a short post to illustrate the use of the auto keyword. It’s something really simple from the latest standard that you can use in your programs and it will save you typing time ๐Ÿ™‚ .

So, the auto keyword has always been around, but it was pretty much redundant. ‘auto’ was the default storage duration specifierย of any variable that you declared, even if you didn’t state it as such. That means that it would be allocated space at the start of the enclosing block of code, and deallocated space at the end.

To put it into context, if you didn’t use auto, you’d use extern or static. It’s a way to tell the compiler how long you want the variable available.

So when you wrote:

int x = 67;

It was really:

auto int x = 67;

Since it was the default, it was pretty much never used anywhere (in fact, I don’t think I’ve ever seen it in commercial code).

Now, the meaning of auto has been changed, with the introduction of C++11, to imply that the type of variable declared will be deduced from the initialisation of that variable.

So basically, you can declare a variable, and use auto instead of any kind of type, and the compiler will work out what that variable is supposed to be.

But what’s the point in that?

Good question. Why write:

auto x = 67;

When it’s actually quicker to write:

int x = 67;

?

Well, the beauty of the auto keyword comes in when you look at more complex types.

For example, when you iterate through a standard container, such as a vector, you have to use this annoying long declaration to create your iterator:

std::vector<string>::iterator it = myvector.begin();

Sigh. So much typing!

Instead, you can now just write:

auto it = my vector.begin();

Now how much easier is that?

Personally I love it.

So neat. So simple. So easy to type.

Here’s a little program with some auto variables in it that you can run. The last one shows the old (C++98) way of declaring the iterator as a comment above the new C++11 way.

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    auto message = "Hello World!";

    auto x = 74;
    auto y = 3.142;

    cout << message << endl;
    cout << "x + y = " << (x + y) << endl;

    vector<string> names;
    names.push_back("Bob");
    names.push_back("Bert");
    names.push_back("Blaine");

    //for (vector<string>::iterator it = names.begin() ; it != names.end() ; ++it)
    for (auto it = names.begin() ; it != names.end() ; ++it)
    {
        cout << *it << endl;
    }

    return 0;
}

 

And this is the program output:

auto

2 thoughts on “C++11 Auto Keyword”

    • It’s entirely up to you. Personally, I still use int, char etc. as they are simple types, and don’t require much typing ๐Ÿ™‚ However, for STL iterators and other types that have long definitions the auto keyword is a really nice substitute.

Comments are closed.