1

I'm browsing some code in the net, and I saw this two declaration,

const std::string strFoo = "MyFoo";

and

std::string const strBar = "MyBar";

I'm confused about the different placement of const keyword. What exactly its purpose?

Thanks!

domlao
  • 15,663
  • 34
  • 95
  • 134
  • 5
    Nothing. The language purposely allows initial const for the base type to be either before or after the type, but only for that specific decl form. `const char *` and `char const *` are another such example. The purpose is to declare the immutable state of the aforementioned variable. – WhozCraig Oct 27 '13 at 03:39

1 Answers1

4

In this case it makes no difference.

For more complicated declarations it may make a big difference.

You could say that const applies to what is to the left and if there's nothing there, it applies to what is to the right.

For example using const qualifier on a pointer to int:

const int* ptr1;        // (1.) pointer to const int
int const * ptr2;       // (2.) same as 1.
int* const ptr3;        // (3.) const pointer to int
const int* const ptr4;  // (4.) const pointer to const int
int const * const ptr4; // (5.) same as 4.

For more info on how to read complicated type declarations se this: C Right-Left Rule

Felix Glas
  • 15,065
  • 7
  • 53
  • 82
  • -1 for The Clockwise/Spiral Rule. This rule breaks the order of precedence so it can't even parse declarations like `int a[4][5]`. Also it is overcomplicated. Use Right-Left rule instead: http://ieng9.ucsd.edu/~cs30x/rt_lt.rule.html, which simly follows the order of precedence without wrong assumption about "clockwise direction". – kotlomoy Oct 27 '13 at 09:16
  • @kotlomoy If you parse symbols like `[][]` in a single pass in the spiral, it works. But looking at the link you provided, the right-left rule indeed seems more intuitive (too bad though it doesn't mention on how to handle const qualifiers). I've updated my answer. – Felix Glas Oct 27 '13 at 16:42
  • +1 for edition. `const` qualifiers obey order of precedence, so Right-Left Rule works well. For example, `int const * const ptr4;` - parsing from `ptr4` to the left we get "const pointer to const int". There is one notable ugly exception - for some reason it is allowed to wright `const` to the left of type like here: `const int* ptr1;`. I really don't like this because it breaks order of precedence and consequently Right-Left Rule. – kotlomoy Oct 27 '13 at 18:17