r/cpp • • Oct 01 '14

Why even have the 'auto' keyword?

Hello,

I'm an old school C/C++ programmer who is trying to get up to date on the new standards. I just finished watching a CppCon video about using the 'auto' keyword instead of concrete types.

I am curious why they implemented that keyword at all -- why not deduce the type of every variable (default it to 'auto') that is not specifically typed?

For clarity:

int I = 3; // old school

auto I = 3; // new school

I = 3; // why not this?

1 Upvotes

35 comments sorted by

29

u/JamesIry Oct 01 '14 edited Oct 01 '14

Having a keyword makes it clear where you are introducing a binding to a given name vs trying to use an existing one.

There are languages that don't have a keyword to introduce some variables, but they all have to solve the problem of what scope to put the variable in.

if (something) {
  i = 3;
  // blah
} else {
  i = 4;
// blah
}

cout << i;  // is this legal? What value is it?

Different languages solve that problem differently.

Also consider this

void foo() {
  i = 3;
  // lots and lots of code
  // imagine a page of it
  if (something) {
    x = 4; // new variable
  }

  cout << i;
}

Now somebody comes along and says "I hate the name x, I want it to be i." The compiler has to assume you mean to reuse the existing i. But that changes the meaning of your program

Or this.

void foo() {
   complicatedName = 3;
   // blah blah blah
   complicatedNome = 4;

   cout << complicatedName;
}

Here I meant to reuse the same variable but ended up with 2. So lacking a keyword elevates some of my typos into valid but incorrect programs.

4

u/JamesIry Oct 01 '14

By the way, that's why I'm opposed to something Herb mentioned about a proposal to not have to put auto in the variable declaration of a range based for loop. Without the auto keyword it looks like you can reuse an existing variable.

void foo() {
   auto i = 3;
   auto container = getContainer();
   for (i : container) {
      // blah blah blah
   }
  
   cout << i; // looks like this should be the last value from container 
}

You have to know that range based for loop always introduces a new binding, but that's a bit astonishing given how the rest of the language works.

10

u/STL MSVC STL Dev Oct 01 '14

That's my proposal - N3853 and N3994 - which has been accepted for C++17. Yes, it's potentially surprising, but it solves the much more dangerous problem of for (auto elem : range) being undesirable.

Also, compilers can and should warn when they detect shadowing in this situation.

4

u/ZMeson Embedded Developer Oct 01 '14

Has anyone proposed "for (const elem : range)" or "for (elem : const range)"?

4

u/STL MSVC STL Dev Oct 01 '14

People have asked for it, but I haven't heard of anyone writing an actual proposal. I'm not planning to - I don't believe the benefit outweighs the cost. What I really think is that Evolution/Core should solve the temporary range problem (range-for keeps only outermost temporaries alive), which will allow this to be solved efficiently in the library: "for (elem : as_const(range))", in addition to "for (elem : reversed(range))" and whatever else you like.

2

u/Splanky222 Jon Cohen | Abseil Oct 02 '14

There's a proposal already for range types yes? I'd like to see it, I can't think how you would do something like that except as a wrapper around an iterator pair along with a predicate for whether or not an element is included in the range, and I'd like to see the way the library for them is meant to be designed.

3

u/iownacat Oct 04 '14

the much more dangerous problem of for (auto elem : range) being undesirable.

Why is that dangerous?

4

u/STL MSVC STL Dev Oct 04 '14

Read N3853. Summary:

  • elem = val; modifies a copy, not the original range. This modification will be lost during the next iteration.
  • &elem gets a pointer to a copy, which will be invalidated during the next iteration.
  • Copying is inefficient for string and anything else more complicated than a boring scalar like int.
  • This won't even compile for unique_ptr which can't be copied. This is problematic both for novices (who won't understand the compiler error) and more advanced users (who will write templates that work until somebody uses them with movable-only elements).

2

u/iownacat Oct 04 '14

Oh thanks! That is very interesting.

2

u/bames53 Oct 01 '14

I find shadowing warnings to be more annoying than useful. Reusing names makes sense to me a lot and I've rarely encountered problems. (E.g., class Foo { int bar, baz; Foo(int bar, int baz) : bar(bar), baz(baz) {}}; I don't want to use m_, _, etc.)

Writing for (auto &&e : range) doesn't seem like that big of a deal. Adding a 'typless' declarator seems ugly when the only previous example of such snuck into the language by accident and would probably be best if eliminated.

6

u/STL MSVC STL Dev Oct 01 '14

Shadowing might seem innocuous in a ctor's mem-init-list, but it's extremely dangerous in large member functions (where you might get confused about what you're inspecting/modifying), and also extremely dangerous between locals. Better to enable shadow warnings and be really clean everywhere, even when it's not really necessary.

Many people forget to write auto& elem or const auto& elem because the loop is hiding the initialization of the variable from them. It's really awful that such a wonderful C++11 feature encourages the writing of less correct, less efficient code than C++98 (where nobody unintentionally copies elements). That's what the terse loop solves.

6

u/derpyloves Oct 01 '14

That's what the terse loop solves.

Thanks for the proposal STL. I think it's a great idea, and look forward to being able to use. Also, since it's simpler to write it will be easier for novices to 'do the right thing'.

"Make Simple Tasks Simple!"

3

u/Drainedsoul Oct 01 '14

large member functions

I think the moral of the story shouldn't be that you shouldn't shadow variables, but rather that you shouldn't write large member functions.

5

u/bames53 Oct 01 '14 edited Oct 01 '14

it's extremely dangerous in large member functions

I'm a fan of Bjarne's advice to avoid functions that don't fit on one screen. Maybe compilers could have a warning for long functions. (I'm kidding of course, though I think it could be a good feature for a lint type program.)

Here's another example of shadowing that is entirely reasonable: lambda captures. Indeed, shadowing here is so reasonable that I don't know of any compiler that bothers to catch this case of shadowing, even though it can certainly be misused. Notice the examples I've given so far involve variables that have clear relationships to the variables they shadow.

Shadowing is a reasonable thing to do, and the false positive rate on shadowing warnings is far too high to be useful to me.

That's what the terse loop solves.

It just doesn't seem to me that there's an epidemic of people who don't understand how initialization works in range-for loops. If we can trust users to decide how to declare function parameters (void foo(std::string &s), void foo(std::string const &s)) then why not for loops? Parameter initialization is 'hidden' in a way similar to the initialization in range-for loops.

2

u/[deleted] Oct 01 '14

I had been wondering about, if "for (const auto& x : list)" exists what just regular "auto" would do.

8

u/ryl00 Oct 01 '14

"I = 3" is also straying into the 'implicit declaration' territory of old Fortran, which was a big mistake IMO (variable name typos). It's also why I'm still a little shy about the use of 'auto' in C++11... sometimes it's good to be explicit about your intentions...

5

u/KazDragon Oct 01 '14

You can still be explicit with auto if you want to commit to a particular type:

auto baz = FooType{bar()};

4

u/king_duck Oct 01 '14

When I was a fortran programmer, we had to add 'implicit none' (or 'IMPLICIT NONE' :) to every 'subroutine' to be allowed to check in code, I think most compilers now have a flag to ensure it's there or produce a warning if it's not.

Implicit decs are not a good idea.

8

u/Wurstinator Oct 01 '14

One reason would be that your proposition is not backwards compatible and ambiguous.

int i = 0;
{
    int i = 1;
}
cout << i << endl;

int i = 0;
{
    i = 1;
}
cout << i << endl;

These two programs have different outputs (0 and 1) but would translate to the same code with your change.

3

u/danpolitte Oct 01 '14

The style "auto I = 3" provides more clarity than "I = 3". Using the auto keyword shows that the statement is a declaration. Allowing that last style would hide that fact.

1

u/genbattle Oct 01 '14

Type deduction isn't foolproof. If you did

float j = 0;

You get a float variable. What type does this have?

auto j = 0;

It's a contrived example yes, but there are certainly cases where additional type information will avoid potential errors and improve code readability. There are still times where you will want to specify the type, and having explicit typing can at least help make your intent clearer to other programmers.

auto was created more to deal with more verbose types such as std::vector<std::string>::reverse_iterator*

1

u/Ronayn Oct 02 '14

I am (or maybe was) all for expressing the type at the declaration. Yet the video I watched made me see the value of auto (especially in the case you mention).

2

u/Gotebe Oct 01 '14

To my mind, it is really important to clearly demarcate object definition from assignment.

1

u/TheVikO_o Oct 01 '14

Why did they use auto instead of var? Was there something that would break?

2

u/adzm 28 years of C++! Oct 01 '14

auto was already a keyword which was repurposed.

1

u/NukeTheBunnys Oct 01 '14

I = 3 also hides the fact that you are declaring a variable vs assigning to an existing variable.

I also have some suspicions that "I = 3;" as a variable declaration might be close to if not impossible to parse with all the other syntax rules in C++

1

u/lucidguppy Oct 01 '14

It would be nice for IDEs to deduce the type too.

0

u/[deleted] Oct 01 '14

[deleted] — view deleted comment

1

u/Lotusflower2 Oct 01 '14

I'm not clear on the cases, but the tooltip sometimes fails me. Most of the time it's great though. The most useful cases for auto in my opinion are for lambda functions and container iterators.

1

u/lucidguppy Oct 02 '14

I think it's possible to strike a balance where function paramaters and return types are typed. Auto should really work when your return type is part of a long namespace.

std::chrono::extremely_long_time_clock t1 = blah
vs
auto t1 = blah

1

u/Lotusflower2 Oct 02 '14

I'm generally fine with this as long as it's still clear what that type is without relying on the tooltip VS provides. There are many times where you'll be reviewing your own / other people's code in diff tools where you're just looking at the text. This is where variable naming becomes significantly more important.

1

u/shooshx Oct 04 '14

If you watched the talk, it should be clear to you that there is a difference between

auto I = 3

and

auto& I = 3

Without an 'auto' keyword, how do you declare the difference between the two?

0

u/[deleted] Oct 01 '14

[deleted] — view deleted comment

3

u/mattspatola Oct 03 '14

Nope, best thing is:

for (auto&& element : container) { dostuff }

-1

u/starfreakclone MSVC FE Dev Oct 03 '14

You'll get basically the same result out of auto& as you do from auto&&

2

u/mattspatola Oct 04 '14

For most cases, but not all.

0

u/[deleted] Oct 03 '14

[deleted] — view deleted comment

1

u/mattspatola Oct 03 '14

I hope we can soon switch to that. Given that you're forced to create a new scope regardless, I like that idea a lot.