auto
, static
, register
and extern
are storage class specifiers, we can only use one of these four in a declaration.
Register: The
variable is to be stored in a machine register, instead of memory (for example,
instead of the stack) . This is useful if we want to use the variable very frequently. Practically, the compiler will do its own
optimization and the
keyword will probably have no effect.
Static: The variable
will be in file scope, so it is accessible within the compilation unit (Compare: a global variable can be accessed from any compilation with external linkage,
and a local variable can be accessed only within block).
Auto: The variable will be in local block-scope, since this is by default any way, auto is
basically not necessary to use. However, in C++11, auto has new meaning: the definition of a
variable with an explicit initialization can use the auto keyword.
Example:
std::list<int> a;
// fill in a
for (auto it =a.begin(); it!= a.end(); ++it) {
// Do stuff here
}
No comments:
Post a Comment