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?
It is rarely used; it meant a local variable. Modern compilers such as VS2010 C++ give it a new meaning.
This answer is wrong, see following question, I'm leaving the answer here as a reference.
AFAIK C++0x's use of auto
doesn't contradict C traditional usage of auto
. In C auto
is used together with the type.
auto char c1 = 'a'; // OK, old meaning of auto is still valid
auto c2 = 'b'; // OK, new meaning of auto (deduce c2 is a char)
The only place where it can change the meaning of the code is when auto was used together with the implicit int
rule (if not type is specified -> it's an int
) in which case the second line in my example used to have c2
of type int
and now it's of type char
.
Bjarne Stroustrup mentions in his C++0x FAQ about auto
:
"The old meaning of auto ("this is a local variable") is redundant and unused. Several committee members trawled through millions of lines of code finding only a handful of uses -- and most of those were in test suites or appeared to be bugs."
So I assume, that compilers wil not be forced by the standard to implement the old meaning of auto
.
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.
In C, auto
specified automatic storage duration (as opposed to static
, extern
, register
). Since this is the default, I have never seen auto
used in any code. I haven't done much C, though.