Chapter 1. Constant Magic

Table of Contents

Arrays and string literals
When constant is stored

Everything you want to know about constants. Pointer to constants, constant members and constant memberfunctions. Const_cast and mutable. When phisical and logical constants are different?

Arrays and string literals

Be carefull the difference between character arrays and string literals. Arrays are alwais allocated in the user data area, and they are mutable, string literals, however, has type const char array, and they are frequently allocated in read-only areas. Modification attempt of such literals can cause run-time errors.


#include <iostream>

int main()
{
    // declaration of three arrays in the user data area
    // read and write permissions for the elements:
    char t1[] = {'H','e','l','l','o','\0'};
    char t2[] = "Hello";
    char t3[] = "Hello";

    // declaration of two pointers in the user data area
    // read and write permissions for the pointers
    // ...and...
    // allocation of the "Hello" literal (possibly) read-only
    char  *s1 = "Hello";    // s1 points to 'H'
    char  *s2 = "Hello";    // ... and s2 likely points to the same place  

    void  *v1 = t1, *v2 = t2, *v3 = t3, *v4 = s1, *v5 = s2;
    std::cout <<v1<<'\t'<<v2<<'\t'<<v3<<'\t'<<v4<<'\t'<<v5<<std::endl;
    // the result (v1, v2 v3 are different, v4 and v5 could be the same):
    0xbffff460   0xbffff450    0xbffff440   0x8048844   0x8048844

    // assignment to array elements:
    *t1 = 'x'; *t2 = 'q'; *ct = 'y';

    // modifying string literal: could be segmentation error:
    *s1 = 'w'; *s2 = 'z';

    return 0;
}


/////////////////////////////////////////////////////////////////


#include <iostream>

int main()
{
    char  t[] = "Hello";
    const char ct[] = "Hello";

    // the type of "Hello" is const char[6]
    // const char[] --> char* conversion is
    // only for C reverse compatibility
    char  *s1 = "Hello";    // line 12: warning

    // this is the correct C++ way:
    const char  *s2 = "Hello";

    // this program produce warnings:
    2_const.cpp: In function `int main()':
    2_const.cpp:12: warning: invalid conversion from `const void*' to `void*'
    2_const.cpp:17: assignment of read-only location


    void  *v1 = t, *v2 = ct, *v3 = s1, *v4 = s2;    // line 17: warning
    std::cout << v1 << '\t' << v2 << '\t' << v3 << '\t' << v4 << std::endl;
    *t = 'x'; *ct = 'y'; *s1 = 'w'; *s2 = 'z';

    return 0;
}


/////////////////////////////////////////////////////////////////


#include <iostream>

int main()
{
    char  t[] = "Hello";
    const char  *s1 = "Hello";

    *t = 'x';
    *s1 = 'w';  // line 12: syntax error

    return 0;
}

// this program won't compile:
3_const.cpp: In function `int main()':
3_const.cpp:12: assignment of read-only location