Reputation: 26365
Suppose I have something like this:
namespace {
const unsigned MY_UINT = 100u;
const float MY_FLOAT = 0.f;
const char* MY_STRING = "Hello World";
}
Do I get expected behavior by using auto
for these? I presume this is an improvement, but I'm not sure about this in practice.
namespace {
auto MY_UINT = 100u;
auto MY_FLOAT = 0.f;
auto MY_STRING = "Hello World";
}
Are the two code examples semantically the same? Will these be const
automatically? If not, should I specify auto const
?
Upvotes: 1
Views: 133
Reputation: 903
No, they are not the same.
When you type:
auto var = 123u;
It is the same as:
unsigned var = 123u;
To achive
const unsigned var = 123u;
You should write
const auto var = 123u;
Do not expect from auto too much. Some kind of magic guesses.
Upvotes: 1
Reputation: 4838
Yes, you must manually specify it const
.
No, it is not a good practice. You generally shouldn't overuse auto
. That keyword can be helpful if name of type is very long but typedef
is often better solution. Auto
obscures code. Moreover, this facilitates errors. Sometimes the type that deduce the compiler may not be the same as what you mean.
You can use auto
if you want but better don't do it without a reason.
Upvotes: 1
Reputation: 96810
auto
's deduction rules are equivalent to by-value template argument deduction. Creating an object by value entails stripping references and top-level cv-qualifiers from the initializer. Your two examples are not equivalent. In particular, the primitive 100u
is of type unsigned int
, so that's what it is deduced as. Likewise, 0.f
is of type float
.
Adding const
only makes sense if the variable itself will not be modified. If you want to make constants in your program, using constexpr
might be better.
Upvotes: 3