I am moving towards C++11 from C++98 and have become familiar with the auto keyword. I was wondering why we need to explicitly declare auto if the
auto could be dropped in some cases, but that would lead to inconsistency.First of all, as pointed, the declaration syntax in C++ is . Explicit declarations require some type or at least a declaration keyword in its place. So we could use var or declare or something, but auto is a long standing keyword in C++, and is a good candidate for automatic type deduction keyword.
Is it possible to implicitly declare variables by assignment without breaking everything?
Sometimes yes. You can't perform assignment outside functions, so you could use assignment syntax for declarations there. But such approach would bring inconsistency to the language, possibly leading to human errors.
a = 0; // Error. Could be parsed as auto declaration instead.
int main() {
return 0;
}
And when it comes to any kind of local variables explicit declarations are they way of controlling the scope of a variable.
a = 1; // use a variable declared before or outside
auto b = 2; // declare a variable here
If ambiguous syntax was allowed, declaring global variables could suddenly convert local implicit declarations to assignments. Finding those conversions would require checking everything. And to avoid collisions you would need unique names for all globals, which kind of destroys the whole idea of scoping. So it's really bad.