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


source to share





All Articles