[All]
My top 5 C++11 language features #5 - auto
By: Tim DelChiaro
Abstract: auto is a new keyword in C++11 that provides automatic type inference when declaring a variable and assigning a value
This is a repost of a blog post from Embarcadero's John Thomas. You can get to his blog and the original post by clicking the blog post name below.
auto is a new keyword in C++11 that provides automatic type inference when declaring a variable and assigning a value. Rather than having to know beforehand and specify the variable type, a C++11 developer can use auto to figure out the type for him, for example:
//infers an integer
auto i = 5;
//infers a double
auto d = 5.0;
//note auto infers a double unless the f suffix is used
//infers a float
auto f = 5.0f;
For these intrinsic types it seems overly powerful but where auto really helps simplify C++ programming is when dealing with template classes, for example, I don’t need to know the type used for a C++ container class beforehand when I can just infer it during an assignment.
//infers an int from the template container type
std::vector<int> vi;
auto i = vi[1];
Again, a pretty trivial example but for anyone who has used C++ container classes and the associated iterator support, coding can get very complicated very fast. Here is a common iterator example for the vector of int we just declared.
for(std::vector<int>::forward_iterator fi = vi.begin(); fi != vi.end(), ++fi)
int i = *fi;
With auto this becomes much easier (and readable):
//infers a std::vector<int>::forward_iterator
for(auto fi = vi.begin(); fi != vi.end(), ++fi)
auto i = *fi;
Connect with Us