11

I'm struggling to come up with some consistent rules for myself for when to use 'auto' in a C++ program. Here are my pro/con lists, perhaps you can help me by giving me your input.

Pro:

  • 'auto' is good for avoiding complex and large template declarations (e.g. the classic use case of auto to define the iteration variable over an STL container)

  • 'auto' is good for future-proofing code. For example, if I have an array of ints and I want to change it to unsigned ints, if I've used 'auto' when I refer to elements of that array, things will automatically update. Of course, that would also have occurred had I used a typedef for the array.

Cons:

  • 'auto' makes it hard to read code. I have no idea if the declaration is a pointer or value. I have no idea if it might have a constructor and destructor.

  • 'auto' makes me lazy. I can forget about the types and just write code. But in C++, the types are very important to the semantics of the program.

When does you guys use Auto? and when do you prefer not to use it?

Garis M Suero
  • 7,974
  • 7
  • 45
  • 68
user200814
  • 275
  • 1
  • 3
  • 8
  • 5
    The types are very important *to the compiler*. :P The *names* are what's important for semantics. JMNSHO. – cHao Mar 06 '13 at 17:54
  • 2
    I always use auto except for `size_t` (in loops, i.e. `size_t i = 0,...` this avoids `i` beeing an `int`). The variables should tell what it is and how to use it. it's all about names. – stefan Mar 06 '13 at 17:54
  • 1
    I use auto only when I'm forced to. I think the type is as important as the variable name, the code is a lot more self-describing without auto. – Synxis Mar 06 '13 at 17:58
  • 4
    http://programmers.stackexchange.com/questions/180216/does-auto-make-c-code-harder-to-understand – RiaD Mar 06 '13 at 17:58
  • 1
    My answer justifies use of `auto` for Expression Templates where it is **almost impossible** to write the type manually for complex expressions. http://stackoverflow.com/questions/6900459/the-new-keyword-auto-when-should-it-be-used-to-declare-a-variable-type – Nawaz Mar 06 '13 at 18:04
  • 2
    I believe this[http://programmers.stackexchange.com/questions/180216/does-auto-make-c-code-harder-to-understand/180616#180616] qualifies as a reference to specific expertise (backed up by facts). – Adrian McCarthy Mar 06 '13 at 18:23
  • This question isn't a good fit for StackOverflow. Programmers is better, but it looks like it (or at least a very similar variant) has already been asked. – Cornstalks Mar 06 '13 at 18:42

0 Answers0