博文

目前显示的是 十月, 2015的博文

A bit more about C++ extern and const

We all know in order to make a const variable global we need to use extern both for the definition of this const variable and its declaration.  That means, in file1.cpp we define the variable n in this way: extern const int n = 8;  In file2.cpp we declare n in this way:  extern const int n;  So why do we need extern in file1.cpp when we define the const variable?  It's because const implies internal linkage by default, so your "definition" isn't visible outside of the translation unit where it appears. In this case, by far the best solution is to put the declaration (extern int const n;) in a header file, and include that in both file1.cpp and file2.cpp. The linkage is determined by the first declaration the compiler sees(so become the header file), so the later definition in file1.cpp will have the correct (external) linkage. As an alternative solution, you add extern in both declare and define of the const, to make it external linkage.

One way to remember the difference between char * const pointer and const char * pointer

char * const pointer ; means that the pointer is constant and immutable but the pointed data is not. const char * pointer ; means that the pointed data is constant and immutable but the pointer is not. An easy to think it is the const modifier is always bind to the next closest thing it can. So in char * const pointer ; the const bind to the pointer variable directly, means the pointer itself can not be modified, but the value the pointer pointed to can be modified.   On the other hand, in this case const char * pointer ; the const modifier bind to *pointer, this means the *pointer(which is the value the pointer pointed to) can not be modified while as the pointer itself can be modified.