Tuesday, August 14, 2018

Pointers of String

It is always tricky dealing with string in C/C++, but if we know the rule of evaluation of expression in C++, it's not that hard to understand it.

A string declaration is always evaluated from right to left.  For example, "char *str" is evaluated as "a variable with name 'str' is a pointer (*) of type char".

Another example:

"const char *str" is evaluated as variable str as a pointer of type char that is const (the content is immutable").  (Please remember, "const char .." expression is identical to expression "char const ...")

"char * const str" is evaluated as a variable with name 'str' is a constant pointer to type char, meaning once the pointer is initialized to point to a string, it cannot be changed to point to another string.

"char const * const str" is evaluated as "a variable with name 'str' is a constant pointer to constant char content.  It is a combination to all above.

#include <iostream>


char* str: 
const char* str OR char const *str
char* const str: 
const char* const str: 


#define L(v)       #v << " = " << v

using namespace std;

static char cstr[] = "String ini statis!";

int main()
    char*   ps1;  // just a regular pointer to a string
    ps1 = cstr;
    cout << L(ps1) << endl;

#if 0
    char const * p_constr = cstr;
    // the following causes compile error, as it tries to change value of the static string
    *p_constr = '1';
    cout << L(p_constr) << endl;

    // a dialect of the above (char const *)
    const char* p_constr2 = cstr;
    *p_constr2 = '1';
    cout << L(p_constr2) << endl;

#if 0
    const char* const const_ptr = cstr;  // the pointer cannot be set to different one

    // the following will cause compile error
    const_ptr = cstr2;
    cout << L(const_ptr) << std::endl;