Note this question was originally posted in 2009, before C++11 was ratified and before the meaning of the
auto
keyword 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?
The auto keyword is a simple way to declare a variable that has a complicated type. For example, you can use auto to declare a variable where the initialization expression involves templates, pointers to functions, or pointers to members.
auto: This is the default storage class for all the variables declared inside a function or a block. Hence, the keyword auto is rarely used while writing programs in C language. Auto variables can be only accessed within the block/function they have been declared and not outside them (which defines their scope).
Here it is very good, as it reduces the use of keyboard, without reducing the readability, as anyone can know the type of objects being created, just by looking at the code.
In C++11, auto can be used for declaring local variables and for the return type of a function with a trailing return type. In C++14, auto can be used for the return type of a function without specifying a trailing type and for parameter declarations in lambda expressions.
In C++11, auto
has new meaning: it allows you to automatically deduce the type of a variable.
Why is that ever useful? Let's consider a basic example:
std::list<int> a; // fill in a for (auto it = a.begin(); it != a.end(); ++it) { // Do stuff here }
The auto
there creates an iterator of type std::list<int>::iterator
.
This can make some seriously complex code much easier to read.
Another example:
int x, y; auto f = [&]{ x += y; }; f(); f();
There, the auto
deduced the type required to store a lambda expression in a variable. Wikipedia has good coverage on the subject.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With