Home > C++, C++0x, News > The C++0x auto keyword

The C++0x auto keyword

You know the C++ auto keyword? The somewhat pointless one which is the default storage specifier anyway? Well in C++0x, the keyword has been re-purposed and now serves a more useful role!

(Remember, this is a feature of the upcoming standard, so it won’t necessary be widely supported yet. However, I have successfully compiled all the code below – apart from bits specifically designed to create errors – in both MSVC and MinGW.)

Consider the following code.

#include <iostream>
#include <string>

int main()
{
	auto a = 4;									// compiler makes 'a' of type int
	auto b = "Hello there!";					// 'b' is of type const char*
	auto c = std::string("Hello to you too!");	// 'c' is of type std::string

	// we can check, too
	std::cout << "'a' is of type " << typeid(a).name() << " and value '" << a << "'." << std::endl;
	std::cout << "'b' is of type " << typeid(b).name() << " and value '" << b << "'." << std::endl;
	std::cout << "'c' is of type " << typeid(c).name() << " and value '" << c << "'." << std::endl;

	return 0;
}

This code results in the following output:

'a' is of type int and value '4'.
'b' is of type char const * and value 'Hello there!'.
'c' is of type class std::basic_string<char,struct std::char_traits<char>,class
std::allocator<char> > and value 'Hello to you too!'.

As you can see, we can declare variables as auto and let the compiler decide on their actual type from the initializer! Pretty cool, no?

There is just one thing to bear in mind. Suppose we add the following code and recompile.

	auto d;
	std::cout << "'d' is of type " << typeid(d).name() << " and value '" << d << "'." << std::endl;

If we try this, we get this error in Visual Studio (and a similar one with MinGW)

error C3531: 'd': a symbol whose type contains 'auto' must have an initializer

and Visual Studio will also generate the following IntelliSense error:

IntelliSense: cannot deduce 'auto' type (initializer required)

Now if we think about it, this makes sense, right? I mean, the auto keyword is telling the compiler to work out the type of the variable. But if there’s no initializer, then it can’t possible work it out. And if you’re thinking it could work it out later when there’s an assignment, then I can think of at least two problems with this:

  1. type conversions can occur during assignments, which could result in a lot of confusion in this circumstance
  2. the statement auto d; is telling the compiler to reserve a memory location for this variable and how can it do that if it doesn’t know how big the type is?

That’s all for now. I hope you’re all enjoying the C++0x features seeping down to us as much as I am!

About these ads
  1. 24.05.2011 at 16:55 | #1

    That was good but I think u are saying a thing that’s not possible for compiler. When u use auto keyword it decides by the variable value and when there isn’t any value it can’t decide what type of variable should be defined.

    Exactly like PHP but PHP doesn’t throw any error for that.

    Check your email BTW !!!

    • 24.05.2011 at 17:28 | #2

      I’m sorry – I don’t quite see where you are going with this. Which bit are you saying is impossible for the compiler?

      And I don’t know about PHP, but I know that in JavaScript, one defines all variables with the ‘var’ keyword, regardless of type.

      I did get your email. Really sorry I haven’t replied yet… I was revising the the English literature exam I have today. Now that’s out of the way, I was meaning to reply tonight :)

  2. 24.05.2011 at 17:55 | #3

    I said the auto variable name part. You know the auto word defines the auto type of variable by it’s value and for that when there isn’t any value, it cant decide what should it do.

    In PHP we define variables like this:

    $variable = value;

    there isn’t any type for it and it decide by the value of variable like

    $variable = “Mahan”;
    $variable = 2;

    and so on…

    I think the cpp compiler must accept some changes… :)

    No prob, I’ll waiting because I made a good content but first you should visit it.

    • 24.05.2011 at 18:01 | #4

      The C++ compiler can do that too, or at least it can if it abides by the new C++0x standard (which isn’t actually released yet).

      The problem comes when you don’t provide a value. In PHP, could you do this:
      $variable
      (i.e. no value). In C++ we can do this, and in such a circumstance the compiler cannot possibly work out the type for itself. Thus we must either use an initializer ( = value) or define the variable with a specific type rather than auto.

  3. xander333
    24.05.2011 at 18:40 | #5

    Seems to be a nice little feature :O
    Although I do wonder where it really serves it purpose in a static and strongly typed language like C++?

    • 24.05.2011 at 19:13 | #6

      On his FAQ, Dr. Stroustrup says it is “most useful when that type is either hard to know exactly or hard to write”.

      His first example is an STL iterator, which of course is tedious to write; his second is a template function which multiplies two numbers: the return type is whatever you get by multiplying the two template types. It is hard for a programmer to know this in general, but easy for the compiler to work it out for particular instances of the template.

      An improvement on the first point has just occurred to me. In my ResourceManager, I have various std::maps which relate URIs to resources. I typedefed the std::map so that if I change the map, the iterators change too. If I made the iterators ‘auto’, I wouldn’t have to worry about it at all, as the compiler would decide on an iterator for me.

  4. xander333
    25.05.2011 at 06:39 | #7

    I see. Seems like I’ll be using it quite a bit in the future ^^

    • 25.05.2011 at 07:31 | #8

      I’ll be using it as well – it is going to really tidy up STL elements of my game engine. However, I think I’m going to make a second post on it, explaining why beginners shouldn’t just use “auto” all the time rather than other types, which they might ;) I think it’s really only meant for tidying what would otherwise require complex notation.

  1. 12.06.2011 at 08:21 | #1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 76 other followers

%d bloggers like this: