4

I'm an experienced programmer but new to C++. I'm following the C++ Primer fifth edition text book and it encourages the use of the 'auto' keyword in range based for loops. For example:

string s = "hello";
for (auto c : s){
    //do some stuff
}

instead of

string s = "hello";
for (char c : s){
    //do some stuff
}

While this is certainly convenient, I don't see why it's sensible to use auto when the actual type is known. Or is there some special case where the type may not be known? I've looked around the web and this does indeed seem to be the done thing, but I couldn't find a good explanation. And the otherwise excellent book hasn't offered one so far either.

Can you help? Thanks!

Edit: Turns out there are many discussions on this already. Some are linked to in the comments. Thanks for the tips.

  • is it actually correct to declare a variable without any type? – mangusta Aug 10 '14 at 16:46
  • 4
    [Almost Always Auto](http://herbsutter.com/2013/08/12/gotw-94-solution-aaa-style-almost-always-auto/) – chris Aug 10 '14 at 16:47
  • 1
    @mangusta: That's not what `auto`does. – Deduplicator Aug 10 '14 at 16:47
  • 1
    `char` sometimes works, `auto` always works. For consistency's sake always use auto. Also the type may be something like `std::vector::const_iterator` which is just annoying to type. – nwp Aug 10 '14 at 16:49
  • @Deduplicator i know what auto does, but is it actually syntactically correct to skip an iterator type ? – mangusta Aug 10 '14 at 16:49
  • You don't "skip" the type, you let the type be automatically deducted. – nwp Aug 10 '14 at 16:50
  • @mangusta If you don't know what auto means, perhaps it's time to find out – David Heffernan Aug 10 '14 at 16:50
  • Many relevant Q&A: https://stackoverflow.com/questions/tagged/c%2b%2b%20auto%20-c?sort=votes Especially the first one: https://stackoverflow.com/questions/6434971/how-much-is-too-much-with-c0x-auto-keyword – Deduplicator Aug 10 '14 at 16:51
  • @mangusta, There are no iterators anywhere except hidden in the implementation of the loop, and no types are being skipped. – chris Aug 10 '14 at 16:51
  • `auto` improves encapsulation, is easier to maintain (e.g. if the container type change) and allow for more consistency over your code. – quantdev Aug 10 '14 at 16:51
  • @DavidHeffernan so far i thought that `auto` is a default storage type for local variable in c++ in case if it has been declared neither `static`, nor `extern` nor `register` – mangusta Aug 10 '14 at 16:53
  • @mangusta: It was the automatic storage-class in C++ prior C++11, just like it still is in C, even though Stroustroup always wanted to repurpose it for type-deduction. – Deduplicator Aug 10 '14 at 16:54

0 Answers0