Lesson 33 +10 XP

The auto Keyword

The auto Keyword

Writing out a type is usually a good thing. But sometimes it's obvious - and that's where auto steps in.

auto deduces the type

auto lets the compiler figure out the type from the initializer. You say auto, the compiler looks at the value on the right, and picks the matching type for you:

auto x = 5;        // x is int
auto y = 3.14;     // y is double
auto z = 'c';      // z is char
auto flag = true;  // flag is bool

The auto deduces the type. Every one of those lines has a fully known type - you just didn't type it out.

auto always needs an initializer

Because auto learns the type from the value on the right, there must be a value:

auto x = 5;   // fine: int deduced
auto y;       // ERROR: nothing to deduce from

No initializer, no deduction, no type - compile error.

When auto helps

auto shines when the type is long or annoying to write. Iterating over a big container is a classic example where the real type is a mouthful:

auto it = myVector.begin();   // type is huge; auto keeps it clean

The caveat: don't overuse it

Readability matters more than a few saved keystrokes. If the type is part of the meaning - like double when precision matters - write it out:

auto x = 5;              // fine, obvious
double result = x * 2;   // better: the type carries meaning

A rule of thumb: use auto when the type is tedious or obvious, and write the type when it explains the code.

TL;DR

  • auto deduces the variable's type from its initializer.
  • auto x = 5; makes x an int; auto y = 3.14; makes y a double.
  • auto requires an initializer - there's nothing to deduce without one.
  • It's great for long, ugly types.
  • Don't overuse it: write the type when it adds meaning.