C ‘auto’ Keyword – Purpose and Usage

c++c++11

What is the goal of the auto keyword in C? With C++ 0x it got new meaning but does it mean that my code will break if I port C code over to a C++ 0x compiler?

Best Answer

It will break if your code contains the auto keyword. In nearly 30 years of C and C++ programming I've never come across any that did. The keyword was introduced in the first C compiler to specify local function variables, but compilers almost immediately became clever enough not to require it, and very little code that uses it will survive today - that's why C++0x chose to recycle it rather than introduce a new keyword which would cause portability problems.

The purpose of the auto keyword in C++0X is to allow the compiler to work out the type of a variable, where this is possible:

vector <int> v;
auto it = v.begin():

the compiler can see that v.begin() must return a vector<int>::iterator and so can create a variable of that type, saving a lot of keyboarding or typedef creation.