Watch, Follow, &
Connect with Us

JT @ Embarcadero

My top 5 C++11 language features #5 - auto

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;

Posted by J T on November 12th, 2012 under C++, C++11, C++Builder, ISO C++ |



One Response to “My top 5 C++11 language features #5 - auto”

  1. JT @ Embarcadero » Top 5 C++ language features #5 – auto : Atom Wire Says:

    [...] JT @ Embarcadero » Top 5 C++ language features #5 – auto Posted in: C / C# / C++ [...]

Leave a Comment

You must be logged in to post a comment.



Server Response from: BLOGS1