In C ++, why use "auto" in a loop based range?

I am an experienced programmer but new to C ++. I am following the C ++ Primer 5th edition tutorial and it encourages the use of the "auto" keyword in a loop based range. For example:

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

      

instead

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

      

While this is certainly convenient, I don't understand why it is smart to use auto when the actual type is known. Or is there some special case where the type cannot be known? I looked around the net and it really looks like what has been done, but I couldn't find a good explanation. And an otherwise excellent book has yet to offer one.

You can help? Thank!

Edit: It turns out there is already a lot of discussion about this. Some of them are related to comments. Thanks for the advice.

+3
c ++ auto


source to share


No one has answered this question yet

Check out similar questions:

23498
Why is processing a sorted array faster than processing an unsorted array?
8499
What is the "->" operator in C ++?
4247
The definitive C ++ guide and book list
3076
What are the differences between a pointer variable and a reference variable in C ++?
2437
Why "using the std namespace;" considered bad practice?
2116
Why are stigmental additions much faster in individual cycles than in combined cycles?
1709
How can I profile C ++ code running on Linux?
1675
Why is reading lines from stdin much slower in C ++ than Python?
1643
Why templates can only be implemented in a header file?
1138
Why do we need virtual functions in C ++?



All Articles
Loading...
X
Show
Funny
Dev
Pics