CS 70

C++'s auto Keyword

  • Pig speaking

    I want to learn MORE C++ syntax!!!

  • Hedgehog speaking

    Nooo!!! Not something else that I have to try to figure out how to use!

  • LHS Cow speaking

    It's not too complicated. And you don't have to use it at all!

Instead of writing…
double* past_end = values+MAX_SIZE;
for (double* p = value; p != past_end; ++p) {
    std::cout << *p << "\n";
}
…we could have used the `auto` keyword, as in
auto past_end = values+MAX_SIZE;
for (auto p = value; p != past_end; ++p) {
    std::cout << *p << "\n";
}

The key here is that the C++ compiler already knows what the type of, say, values+MAX_SIZE, is, so rather than have to write double* ourselves, we can let the compiler figure it out, automatically.

If you declare a variable with auto, then it will have the type of whatever value the variable is initialized with.

  • Duck speaking

    So it's more like Python, where I didn't have to say the types.

  • Python speaking

    Actually, no. Python lets you change what type of thing is in a variable from moment-to-moment (helping to maximize surprise!). C++ doesn't let you do that.

Using auto does not mean that a variable can change type during runtime. It just means that the compiler will figure out the type of the variable at compile time. There still has to be a unique correct type for the variable.

Using auto Sparingly

Using auto can declutter code, but it can also make code harder to understand.

For example,

auto x = mysteryFunc1();
auto y = mysteryFunc2();
auto z = mysteryFunc3(x,y);

is much less clear than

Fish x = mysteryFunc1();
Water y = mysteryFunc2();
FishTank z = mysteryFunc3(x,y);

Overall, there is some judgement to use in when to omit the types and let C++ figure it out. Much of the time (especially in your homework assignments), it's probably best to specify the type explicitly. In particular, writing

auto numAnimals = 10;

will be inferred by the compiler as

int numAnimals = 10;

and not

size_t numAnimals = 10;

But we'll use it in begin/past-the-end for loops in the rest of this lesson. Using auto lets us not worry about the specific type of the pointer and instead focus on the big concept: iterating over all the items.

  • Hedgehog speaking

    Can I get some guidance on when to use auto?

  • LHS Cow speaking

    Sure!

When to Use or Avoid Using auto

  • Use auto when it improves readability, such as when the type is

    • Complicated
    • Genuinely doesn't matter
    • Clear from context
  • Avoid using auto when the type is

    • Simple and known
    • Important for understanding the code
    • Unclear from context
  • Cat speaking

    By those rules, it seems a bit questionable to use it for a double* type. It's not that complicated.

  • LHS Cow speaking

    True.

  • Goat speaking

    I'm wondering if you've got some ulterior motive here.

  • LHS Cow speaking

    Wait and see!

(When logged in, completion status appears here.)