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*).

Share:
20,204
steffen
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, 2020

Comments

  • steffen
    steffen over 3 years

    Is there a semantic difference between auto const and const auto, or do they mean the same thing?

  • Seshadri R
    Seshadri R over 5 years
    If there is nothing left, then it is right (and vice versa) :-)
  • Arne Vogel
    Arne Vogel over 5 years
    That'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 of const.
  • 4LegsDrivenCat
    4LegsDrivenCat over 4 years
    @ArneVogel OMG, why typedef is allowed in the middle :)
  • jbruni
    jbruni over 4 years
    The const doesn't really apply to char*, it applies to the char part, not the * part.
  • WillY
    WillY over 4 years
    As @ArneVogel commented, the answer is not completely correct. The fact that this is the accepted answer is misleading (and possibly dangerous).
  • Krapnix
    Krapnix over 3 years
    @ArneVogel where could I read more about this please