Note this question was originally posted in 2009, before C++11 was ratified and before the meaning of the
autokeyword was drastically changed. The answers provided pertain only to the C++03 meaning ofauto— that being a storage class specified — and not the C++11 meaning ofauto— that being automatic type deduction. If you are looking for advice about when to use the C++11auto, this question is not relevant to that question.
For the longest time I thought there was no reason to use the static keyword in C, because variables declared outside of block-scope were implicitly global. Then I discovered that declaring a variable as static within block-scope would give it permanent duration, and declaring it outside of block-scope (in program-scope) would give it file-scope (can only be accessed in that compilation unit).
So this leaves me with only one keyword that I (maybe) don’t yet fully understand: The auto keyword. Is there some other meaning to it other than ‘local variable?’ Anything it does that isn’t implicitly done for you wherever you may want to use it? How does an auto variable behave in program scope? What of a static auto variable in file-scope? Does this keyword have any purpose other than just existing for completeness?
autois a storage class specifier,static,registerandexterntoo. You can only use one of these four in a declaration.Local variables (without
static) have automatic storage duration, which means they live from the start of their definition until the end of their block. Putting auto in front of them is redundant since that is the default anyway.I don’t know of any reason to use it in C++. In old C versions that have the implicit int rule, you could use it to declare a variable, like in:
To make it valid syntax or disambiguate from an assignment expression in case
iis in scope. But this doesn’t work in C++ anyway (you have to specify a type). Funny enough, the C++ Standard writes:which refers to the following scenario, which could be either a cast of
atointor the declaration of a variableaof typeinthaving redundant parentheses arounda. It is always taken to be a declaration, soautowouldn’t add anything useful here, but would for the human, instead. But then again, the human would be better off removing the redundant parentheses arounda, I would say:With the new meaning of
autoarriving with C++0x, I would discourage using it with C++03’s meaning in code.