Skip to main content
6 of 6
added 118 characters in body
Christophe
  • 80.6k
  • 11
  • 132
  • 199

It is true that code is being read and maintained more often than it is written.
But that's one more reason to use auto !

auto to accelerate change propagation

For the maintenance of code, auto has indeed often (not always) the advantage of facilitating abstraction and ease decoupling from the types. Take your example:

double totalCost=item1.quantity*item1.price+item2.quantity*item2.price+....

Imagine that you find out that finally double is not sufficiently precise for the price, and you'd need to go for long double to avoid unacceptable loss. You'd have to go carefully through your code, and for every double look if it's concerned by the change or not. With auto, you let the compiler automatically propagate that change and will have less risks of forgetting one occurence.

See online example here.

Of course, type inference has its limits, and sometimes the programmer really has to chose the right type (often with the need of explicit casting some operands already in the expression to really achieve the intended result - see counter example here). Make that the exception, not the rule.

auto to prevent accidental slicing

Type inference also avoids nasty slicing errors, for example when MySpecialisedClass subclass needs to be used instead of MyClass and one declaration was forgotten, e.g:

MySpecialisedClass xyz("some", more, arguments);
... // lots of code 
MyClass uvw = xyz; // still looks fine - but slicing occurs ! 

See online example here demonstrating the advantage of auto.

But what about reading ?

There are a lot of languages with no explicit types specified or type inference similar to auto:

  • JavaScript: In my experience, native experienced JS devs rarely complain about unreadable due to missing type information. The main concern is when accidentally a variable causes a runtime error because of a wrong type. So it's more about type safety than readability.
  • Python, which is strongly but dynamically typed: Python devs that I know, usually don't complain either about the lack of explicit type and type hinting aims at type safety rather than readability as explained in PEP484
  • Many other modern languages promote type inference. For example Rust or Swift, to name only a few. Swift for exemple encourages type inference with let (like const auto) and var (like auto).

Why would the absence of explicit type be more difficult to read if it's C++ then ? My position is that it's because of habits, habits still prevent people to embrace modern C++ and its benefits.

Why not giving a try? Modern IDEs and editors perfectly do the trick in getting used to it. Example with Visual Studio Code, when hovering over an auto declared identified:

enter image description here

Christophe
  • 80.6k
  • 11
  • 132
  • 199