Wednesday, July 30, 2014

C pointer and constant

Review C pointer and constant:
situee.blogspot.com

1. Pointer to Constant Value

const char *ptr = 'a';  OR    char const *ptr = 'a'

"const" precedes the *, that means the pointer treat *ptr  as constant

This is NOT valid     :  
*ptr = 'b';

Another example;

int nValue = 5;
const int *pnPtr = &nValue;

Thus, the following is okay:
    nValue = 6; // nValue is non-const
But the following is not:
    *pnPtr = 6; // pnPtr treats its value as const


2. Constant Pointer

char * const ptr = 'a';

This means the pointer ptr is a constant pointer

This is NOT valid:
char char_B = 'b';
ptr = &char_B;


3. Constant Pointer to Constant Value

const char * const ptr = 'a';  OR    char const * const ptr = 'a';


Reference:


http://www.learncpp.com/cpp-tutorial/610-pointers-and-const/
http://www.cprogramming.com/reference/pointers/const_pointers.html
http://www.noxeos.com/2011/07/29/c-const-static-keywords/
http://www.codeguru.com/cpp/cpp/cpp_mfc/general/article.php/c6967/Constant-Pointers-and-Pointers-to-Constants.htm

No comments:

Post a Comment