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?
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 primitive100uis of typeunsigned int, so that's what it is deduced as. Likewise,0.fis of typefloat.Adding
constonly makes sense if the variable itself will not be modified. If you want to make constants in your program, usingconstexprmight be better.