C++ guru Herb Sutter proposes that we should almost always use "auto". He states this on his website and he recently repeated it at the CppCon 2014 conference.
I've tried to follow his advice and I'm not convinced. Is there someone here who agrees with Sutter and who can tell me why
auto gender = string{};
auto number = string{};
auto person = string{};
is better than
string gender, number, person;
which is what I ended up writing in my code, because I couldn't bear the auto style.
Edit:
auto gender = string{}, number = string{}, person = string{};
is also a possibility, but in my opinion that's even worse.
Good use of auto is to avoid long initializations when creating iterators for containers. Note: The variable declared with auto keyword should be initialized at the time of its declaration only or else there will be a compile-time error.
attribute declaration (C++11) empty declaration. Specifies that the type of the variable that is being declared will be automatically deduced from its initializer. For functions, specifies that the return type is a trailing return type or will be deduced from its return statements (since C++14).
C language uses 4 storage classes, namely: 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.
Although the auto keyword can be used in the function return type, it is usually not used by the programmers in the case of simple functions, as it sometimes creates problems as the return type of function is very useful and returned to the caller, which then performs specific tasks according to the program ...
The auto keyword should mainly be used in cases where you initialize the variable with a value, as this makes the code more maintainable in cases where you change the value you initialize the variable with:
uint16_t id_ = 65535;
uint16_t id()
{
return id_;
}
auto myid = id();
No need to change the type of myid
if id()
return type changes.
And with C++14 it gets even better:
uint16_t id_ = 65535;
decltype(auto) id()
{
return id_;
}
auto myid = id();
Changing the type of id_
automatically adjusts the return type of id()
and the type of myid
.
In cases where the initial value of the variable is not initialized with a value and as such is not dependent on other code for initialization, it makes sense to explicitly define the variable type, as the auto keyword would not add more maintainability to the code and the syntax auto gender = string{};
is less readable than string gender;
.
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