Why prefer declaring variables using auto? Let us count some of the reasons why…



Problem



JG Question



1. In the following code, what actual or potential pitfalls exist in each labeled piece of code? Which of these pitfalls would using auto variable declarations fix, and why or why not?

// (a)

void traverser( const vector<int>& v ) {

for( vector<int>::iterator i = begin(v); i != end(v); i += 2 )

// ...

}



// (b)

vector<int> v1(5);

vector<int> v2 = 5;



// (c)

gadget get_gadget();

// ...

widget w = get_gadget();



// (d)

function<void(vector<int>)> get_size

= [](vector<int> x) { return x.size(); };

Guru Question



2. Same question, subtler examples: In the following code, what actual or potential pitfalls exist in each labeled piece of code? Which of these pitfalls would using auto variable declarations fix, and why or why not?