Is 'auto const' and 'const auto' the same?
20,204
Solution 1
The const
qualifier applies to the type to the immediate left unless there is nothing to the left then it applies to the type to the immediate right. So yup it's the same.
Solution 2
Contrived example:
std::vector<char*> test;
const auto a = test[0];
*a = 'c';
a = 0; // does not compile
auto const b = test[1];
*b = 'c';
b = 0; // does not compile
Both a
and b
have type char* const
. Don't think you can simply "insert" the type instead of the keyword auto
(here: const char* a
)! The const
keyword will apply to the whole type that auto
matches (here: char*
).
Author by
steffen
I am a Python freak and data nerd. Also, I am experimenting with creating videos on youtube. About Python and data. ¯(°_o)/¯ https://www.youtube.com/channel/UCG9XNnq9LodijOBpIVy1ILg
Updated on November 16, 2020Comments
-
steffen over 3 years
Is there a semantic difference between
auto const
andconst auto
, or do they mean the same thing? -
Seshadri R over 5 yearsIf there is nothing left, then it is right (and vice versa) :-)
-
Arne Vogel over 5 yearsThat's not really how it works, specifiers and qualifiers (that precede the declarator) may appear in any order, e.g.
long volatile unsigned const typedef long cvull;
. The type is neither (fully) to the left nor to the right ofconst
. -
4LegsDrivenCat over 4 years@ArneVogel OMG, why
typedef
is allowed in the middle :) -
jbruni over 4 yearsThe const doesn't really apply to
char*
, it applies to thechar
part, not the*
part. -
WillY over 4 yearsAs @ArneVogel commented, the answer is not completely correct. The fact that this is the accepted answer is misleading (and possibly dangerous).
-
Krapnix over 3 years@ArneVogel where could I read more about this please