Home c++ Keyword `auto`

Keyword `auto`




What does the auto keyword mean in and where is it used?

Answer 1, authority 100%

This word is redefined in the new standard and tells the compiler: “Compiler, take and guess the type of this variable!”. The compiler can do it just fine in many cases. This is useful in templates and for iterators.

Once upon a time this word meant something completely different.

Answer 2, authority 97%

Stone Age

The auto keyword means that the variable is in automatic storage and the lifetime of such a variable is local lifetime. In other words, we indicated that this variable is on the stack, but since all variables created in functions like

int a = 10;

is already implied that they are stackable – this is a meaningless keyword.

Since C++ 11

Starting with C++ 11, the auto keyword takes on new life. It tells the compiler at compile time to determine the type of the variable based on the type of the expression being initialized.

# include & lt; iostream & gt;
#include & lt; typeinfo & gt;
#include & lt; vector & gt;
using namespace std;
class Foo
  Foo (int x)
int main ()
  std :: vector & lt; std :: vector & lt; Foo * & gt; & gt; arr;
  auto a = 166LL;
  auto b = 'a' + true;
  auto c = Foo (3);
  auto d = arr.begin ();
  cout & lt; & lt; typeid (a) .name () & lt; & lt; endl;
  cout & lt; & lt; typeid (b) .name () & lt; & lt; endl;
  cout & lt; & lt; typeid (c) .name () & lt; & lt; endl;
  cout & lt; & lt; typeid (d) .name () & lt; & lt; endl;
  return 0;

Output: http://rextester.com/BNNAL62867

Features of auto

  1. The auto variable must be initialized without fail
  2. The auto variable cannot be a member class
  3. The variable auto cannot be a function parameter until C++ 14
  4. The type auto cannot be the return type of a function until C++ 14. http://rextester.com/AFDFD63587


Companions : there are data types in C++ that spoil readability when they are long (about std :: vector iterators, for example) and I would like to write less. For modern C++ under metaprogramming conditions, the ability to return the auto type makes the template flexible.
Opponents : the auto type beats the code readability. We have to guess what the variable is and do an extra action in the IDE by hovering the mouse over to understand what the type is. This kind of “dynamic type” conflicts with the definition that C++ is a strongly typed language.

I’m in favor of using auto in moderation. Don’t go to extremes.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions