首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Where to put the const

2013-02-15 
Where to put the const?In Googles C Style Guide, the location of const is described as follows.Som

Where to put the const?

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.

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

http://en.wikipedia.org/wiki/Const-correctness

http://www.embedded.com/electronics-blogs/programming-pointers/4025641/Qualifiers-in-multilevel-pointers

热点排行