7

C++11 features the new auto type declaration, allowing you to work with an object without ever knowing its actual type.

I use only strongly typed languages - C++, Delphi (Object Pascal), Go, etc and I feel uncomfortable (guilty?) using auto, (or for example the short variable declaration - x:=1- in Go.) It feels like a hack to me - I use strongly typed languages because they ensure that you know what type you're using. (With the exception of the abuse of untyped pointers.) Although certainly I appreciate the benefits: Proper type names involving iterators, templates, smart pointers etc can get very lengthy and a bit difficult to determine and declare explicitly, or to parse when reading. Granted, once you know the proper type name, you can "typedef it", but sometimes getting it right the first time is time consuming and not always so easy.

Or, imagine you that inherit a large, complex project that you need to modify, and every variable possible in that project is declared using auto- you're going to have to do a lot more work to understand that code-base than if everything was declared using explicit types.

So, what are some guidelines on when to use auto and when to sweat it out with full and proper type names? I am currently reading Stroustrup's A Tour of C++ and he himself there in Chapter 1 advocates using auto in situations when you know auto will "get it right":

We use auto where we don’t have a specific reason to mention the type explicitly. “Specific reasons” include:

• The definition is in a large scope where we want to make the type clearly visible to readers of our code.

• We want to be explicit about a variable’s range or precision (e.g., double rather than float).

In the Advice section of Chapter 1 there he also warns:

-Prefer the {}-initializer syntax for declarations with a named type;

-Prefer the = syntax for the initialization in declarations using auto;

This, because default initialization {} could result in an incorrect type initialization.

Still, I feel a bit uncomfortable using auto.

Can anyone perhaps give me some additional guidelines about the use of auto, and/or debunk my impression that auto is a hack of sorts and really should be avoided in favor of determining the proper type and then using atypedef?

Vector
  • 3,180
  • 3
  • 22
  • 25
  • 2
    You have not stated *why* you feel uncomfortable using `auto`. So it's impossible for us to determine whether your reasons are justified or not. – Greg Hewgill May 19 '14 at 00:42
  • I'm not sure there's sufficient difference between languages to keep this and [this](http://programmers.stackexchange.com/questions/42863/c-explicitly-defining-variable-data-types-vs-using-the-keyword-var) (and various others) apart. – Telastyn May 19 '14 at 00:47
  • @GregHewgill - I opened with _allowing you to work with an object without ever knowing its actually type_ and said it feels like a hack, and also elaborated in my conclusion of the question. – Vector May 19 '14 at 00:50
  • 3
    If you have every written a template, you've written code that works with an object without knowing its type. – Gort the Robot May 19 '14 at 00:56
  • @StevenBurnap - indeed - because it's a **template**, which is really an extension of the language itself. You can't **consume** a template that way - you have to use a specific type. – Vector May 19 '14 at 00:58
  • @GregHewgill - I edited... – Vector May 19 '14 at 00:58
  • @Vector `auto` also always creates a specific type. It just does it implicitly. (Which makes it no less strongly typed.) – Gort the Robot May 19 '14 at 01:02
  • @StevenBurnap - sure, it creates a specific type - it's resolved at compile time. But when you write your code, you don't have to know what that type is. The issue is not what `auto` does, but **what you know** about what it does. Nowhere did I say that `auto` is **not** strongly typed. – Vector May 19 '14 at 01:22
  • @Telastyn - I understand where you're coming from but C# is **not** C++ by a long shot - it's an entirely different "breed" in that it compiles to IL, not native code, and it's also essentially proprietary (Mono notwithstanding). I've used C# when my job required it, but on my own I don't use it and I don't care for it. Same with those "various others" you alluded to. (No, **not** looking to get into "language wars" :) ) I'm asking here about C++ in the context of C++ itself. – Vector May 19 '14 at 01:31
  • 1
    @vector - none of those (incorrect) things impact if you should use `auto`/`var` or not. – Telastyn May 19 '14 at 02:00
  • @SK-logic - repeating for the third time: I **never** said auto is not strongly typed, just that you don't explicitey **see** the types. It's important to read the question - at least **the first line...** Note the accepted answer - this discussion is not about if auto is strongly typed, but about when it's important to **specify** the type. – Vector May 19 '14 at 06:24
  • @Vector: the guidelines for using *auto* in C++ correctly are the same as for using *var* in C#. So I recommend to search for postings here on C# about the use of "var" and read the answers - this discussion took place here some years ago. – Doc Brown May 19 '14 at 06:28
  • @SK-logic - see accepted answer, which explains more specifically what you're saying. I understand you like Haskell, but I don't use it and I'm not interested in comparisons to it. The accepted answer deals with C++ on C++'s terms. – Vector May 19 '14 at 06:42
  • @SK-logic - _I argue that such cases are nearly non-existent_ - and on that point I disagree, and I disagree with your characterization of the accepted answer as _misleading_. I prefer to **know** what I'm dealing with when I code. Call me a "control freak"... :) And my impression is I'm by no means alone in the programming world. And there are times, at least in C++ ( I don't know Haskell and can't talk about it) when you must know the type - the use of `auto` is limited. – Vector May 19 '14 at 06:53
  • 1
    `/strongly/statically/g`, [the former means absolutely nothing](http://stackoverflow.com/a/9929697/395760). –  May 19 '14 at 08:34
  • @jwenting - _if you're uncomfortable using something, that's an indication there's some learning to do_ : I'm not sure I get your point: sometimes _there's some learning to do_ not because you're deficient, but because something is opaque and obfuscated. Just because something requires learning doesn't mean that it's good but you haven't caught up - it might mean that thing is designed poorly - you **could** learn how to jam a square peg into a round hole... but that wouldn't make it a good fit. – Vector May 19 '14 at 08:36
  • @jwenting - Do you really think that if someone doesn't know every type and signature in the STL, so that whenever they use `auto` the correct type name immediately pops into their head "has some learning to do" - sure, everyone always "has some learning to do" but I recently read a book by a compiler engineer with a PhD in math and computer science who worked on one of open source C++ compilers, and he mentioned that he sometimes had to refer to the docs and specs for the STL... so... – Vector May 19 '14 at 08:43
  • @jwenting - _but mostly questions/comments/rants like this..._ does this question sound like a rant from someone who doesn't understand what `auto` is used for and why it's there? It was closed as a dup, not because it's a dumb question or a rant. – Vector May 19 '14 at 17:10

2 Answers2

24

No, you should not feel uncomfortable using auto.

Just use it in situations where the type is obvious, or where no one is going to care about it

A classic example (IMO) of where auto is handy:

std::vector<sometype> vec
...
...
//some code
...
...
for(auto iter = vec.begin(); iter != vec.end(); ++iter)
{
   //something here
}

Nobody really cares about the details of the iterator variable (std::vector<sometype>::iterator iter), only that it is an iterator. Explicitly specifying the type just adds visual noise. Often, without auto, people will create typedefs for commonly used iterators, which can obscure issues and lead to some bizzare error messages if you use the wrong typedef.

whatsisname
  • 27,463
  • 14
  • 73
  • 93
  • Excellent guidelines - accepted. – Vector May 19 '14 at 04:58
  • 2
    Just nitpicking: in this case, one might as well use the range-based for-loop instead for better clarity (unless you really need the iterator, and not the value). Perhaps another example would illustrate the point better ? (still +1 for me) – ereOn May 19 '14 at 07:43
  • 1
    (Should even be a range-based for loop for even more goodness.) – Mat May 19 '14 at 08:04
  • 1
    @ereOn: Using iterators announces that the body of the loop will only deal with a single element at a time, whereas indexing you may use multiple by offsetting the index. Each has its advantages. Additionally, while the performance of iterator vs indexing for vectors is pretty much the same, that is not necessarily true for other containers, where one can be significantly faster than the other. http://stackoverflow.com/questions/131241/why-use-iterators-instead-of-array-indices – whatsisname May 19 '14 at 13:14
5

You are still getting strong types even if they aren't explicitly specified. You're going to eventually hit a static type mismatch in most circumstances. The main concern with type inference is accidentally inferring a type too concrete or abstract. In other words, inferring a derived type when you really needed the base type, or vice versa. If it matters what exact type you get, don't use auto.

Another concern about type inference is if it might change the public interface of your code. In general, you should make the types of your public interface explicit.

Aside from those circumstances, there's little reason not to use auto when it simplifies your code.

Karl Bielefeldt
  • 146,727
  • 38
  • 279
  • 479
  • 2
    _You are still getting strong types even if they aren't explicitly specified_ - I never said `auto` is not strongly typed, just that **you don't explicitey see the types**. – Vector May 19 '14 at 03:42
  • @BartvanIngenSchenau - _no right to complain that your type name spans three lines and makes the code unreadable_ Curious to know where you found any mention of a complaint in my question... the creator of C++ himself (cited in the question) advocates using `auto` and gives some guidelines on how to use it - I'm not going to "complain". I asked for clarification on using `auto` because most of us like to know what our code is doing and `auto` feels a bit strange and hacked - meaning that I'm uncertain about its appropriate use, which the accepted answer elaborates on. – Vector May 19 '14 at 17:26
  • 1
    Why is it strange to let the computer handle what the computer knows? `auto` is very useful for situations where the compiler will only accept one value. Why should I waste time figuring out what it knows? It doesn't feel like a "hack" at all to have not have to tell the compiler what it already knows. "This variable should just have whatever type this function returns" seems a lot more reasonable than "I declare this is an `int` but if the function returns something else, tell me that I'm wrong, or maybe implicitly convert in a way that will trip me up" – Gort the Robot May 19 '14 at 17:58
  • 2
    @StevenBurnap _Why is it strange..._ Not sure "strange" is the right word, but the point here is not what the computer knows, but what the programmer knows: Imagine you inherit a large, complex project that you need to modify, and every variable possible in that project is declared using `auto`- you're going to have to do a lot more work to understand that code-base than if everything was declared using explicit types. – Vector May 20 '14 at 11:01