[C/C++] ‘const’ keyword.

Using ‘const’ wherever possible is very very important. It can help to avoid mistakes and increase readability very much.
Personally, I even regard ability of using ‘const’ in code, as one of most important evidence to evaluate programmer’s quality.

==== const member function ====

class A {
    void funcB(void) const;
    void funcA(int* pa) const;
    int* funcC(void) const;
    int a

const member function(henceforth const member) cannot change class member variable. And, const member can call only const member. But, const member can call any C function.
By the way, there is no constraints about parameter in const member. So, following is possible.

Hack 1
  void A::funcB(void) const { funcA(&a); }
  void A::funcA(int* pa) const { *pa = 9; }

Hack 2
  void A::funcB(void) const ( int* p = funcC(); *p = 8; }
  int* A::funcC(void) const {return &a;}

Even if, funcB changes value of member variable, it compiles well. This is one of week points of const member.

==== const & pointer ====

const int* p;   // *1 - (*p) is const
int const *p;   // *2 - (*p) is const
int* const p;   // *3 - (p) is const

case *1, *2;

“*p = 4” is error, but, “p = &b” is OK.
So, we can hack this like “*((int*)p) = 9;”.

case *3

contrary to upper case. So, we should initialize pointer before using it.

==== const & multiple pointer ====

const int** p;   // *1
int const **p;   // *2
int* const *p;   // *3
int** const p:   // *4

int*       pb;
const int* cpb
int b;

case *1, *2.

// p = &pb; // error – “cannot convert from ‘int **’ to ‘const int **”
p = &cpb; // OK.
*p = &b;
// **p = 8; // error – “you cannot assign to a variable that is const”
*((int*)*p) = 8 // OK. Hack!

case *3

p = &pb; // OK
*p = &b; // error – “you cannot assign to a variable that is const”

case *4

p = &pb; // error – “you cannot assign to a variable that is const”. p should be initialized before used.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s