So I understand using var
in C# makes sense because you have anonymous types that are compiler derived. C++ doesn't seem to have this feature (unless I'm wrong), so what is the point of having an auto
keyword?
(It is kinda cool that unlike C#, auto
does work for member/global variables, which is cool I guess, but doesn't seem enough to justify its existence).
Best Answer
auto
has a lot of uses when it comes down to both generic programming and to save the programmer some typing.For example, consider this. Would you rather type out:
or:
Yes, they're both long but we know the return type and specifying it again is a bit cumbersome to type. This also goes for iterators:
vs:
Its use in generic programming is also to figure out the return type of a function or if you're doing some generic algorithms where you don't know the type.
For example, consider a very basic example.
This allows the compiler to figure out the type of the add operation rather than us trying to figure it out ourselves. Note that in C++14 you can omit the trailing return type. Its uses in generic programming don't stop there either. If we wanted to work with any type of container as a wrapper function for algorithms we could use
auto
to help us with it. For example:In the future (C++14), auto can be used to make polymorphic lambdas as well such as:
Which can be useful as well.