Basically when you use the auto specifier, the compiler looks at the type of the value which was used to initialize the variable. And it declares the variable to be of the type of which the value that was assigned to it was.
So if you wrote: auto foo = 5;
foo would be an integer variable.
Why is this useful? auto can also declare variables as objects so often it's just simply to improve readability. But auto can also be used in cases where the variable could be holding more than one possible type. Sometimes it's a matter of convenience, as it's much easier to type auto.
For the ranged for loop, auto gives row and element the value of integer. Here it can be handy as you can use the bit of code to display an array of anything. Of course you can explicitly declare row and element to be integer, but what if the array is not of integer type? Then you the ranged for loop would fail, on the other hand the ranged for loop with auto would handle this just fine.
@Nwb, you have so little experience you really need to test even the smallest piece of code you show to some unsuspecting fellow beginner. Your code example will not compile (obviously).
#include <iostream>
#include <array>
usingnamespace std;
int main (){
constint rows = 2;
constint columns = 3;
array<array<int, columns>, rows> A1 = {1, 2, 3, 4, 5, 6};
for (autoconst row : A1){
decltype(row)::foo = 1;
// error: 'foo' is not a member of 'std::array<int, 3ul>'
for (autoconst element : row) {
decltype(element)::foo = 1;
// error: decltype evaluates to 'const int', which is not a class or enumeration type
}
}
}
Again:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
#include <map>
#include <vector>
#include <string>
usingnamespace std;
int main (){
const map<string,vector<string>> snafu;
for ( auto foo : snafu ) {
decltype(foo)::bar = 1;
// error: 'bar' is not a member of 'std::pair<const std::basic_string<char>, std::vector<std::basic_string<char> > >'
}
}
That went a bit overboard, but nevertheless:
1 2 3
for ( auto foo : snafu )
// vs.
for ( pair<const string, vector<string>> foo : snafu )
It is easy to get long typenames. You could use aliases, or you could use auto.
On the other hand, you need to know what foo is in order to use it.
Can you remember it from snafu, or do you have to spell it out?
its a tool :)
sometimes it makes code more readable and is handy, and sometimes it makes it harder to follow. If everything you type is of type auto, it can quickly get confusing as to what you have.
I really like autos for letting it decide which of the 8+ integer types is correct.