In Google's C++ Style Guide, the location of const is described as follows.
Some people favor the form int const *foo
to const int* foo
. They argue that this is more readable because it's more consistent: it keeps the rule that const
always follows the object it's describing. However, this consistency argument doesn't apply in codebases with few deeply-nested pointer expressions since most const
expressions have only one const
, and it applies to the underlying value. In such cases, there's no consistency to maintain. Putting the const
first is arguably more readable, since it follows English in putting the "adjective" (const
) before the "noun" (int
).
That said, while we encourage putting const
first, we do not require it. But be consistent with the code around you!
The Wikipedia page on "Const-correctness" gives a rule of thumb that is to read the declaration from right to left. (For instance, int const * can be read as a mutable pointer that refers to a non-mutable integer, and int * const can be read as a non-mutable pointer that refers to a mutable integer.But sadly, this does not apply to the situation where Google's guide points out: multilevel pointers with only one const outside (as highlighted above).
A simple experiment can verify this point: in the code below, the const does not make anything immutable, and the program is able to compile correctly using VS2012.
#include <cstdio>
int main(int const argc, char** const argv) {
argv[0] = argv[1];
argv[0][0] = 'b';
// argc = argc - 1;
for (int i = 0; i < argc; ++i)
printf("%s\n", argv[i]);
return 0;
}
The following two pieces of codes also compile without any errors:
#include <cstdio>
int main(int const argc, char *const argv[]) { // or int main(const int argc, char* const* argv)
// argv[0] = argv[1];
argv[0][0] = 'b';
// argc = argc - 1;
for (int i = 0; i < argc; ++i)
printf("%s\n", argv[i]);
return 0;
}
#include <cstdio>
int main(const int argc, char const ** argv) { // or int main(const int argc, const char* argv[])
argv[0] = argv[1];
// argv[0][0] = 'b';
// argc = argc - 1;
for (int i = 0; i < argc; ++i)
printf("%s\n", argv[i]);
return 0;
}
The both constant version of argv should be something like this (either seems fine):
int main(int const argc, char const* const* argv)
int main(const int argc, const char* const* argv)
int main(const int argc, const char* const argv[])
The first const is const-ing the "char" value, while the second const is const-ing the first-level pointer.
This seems to be pretty twisted and ambiguous. Further investigation of C++ standard is still needed.
References:
http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Use_of_const
http://stackoverflow.com/questions/1621574/mains-signature-in-c
http://stackoverflow.com/questions/3034296/const-qualification-of-mains-parameters-in-c