• 0
    Suppose we have following definitions in C:

    char a;
    const char b='#';
    const char *p1; //pointer to a constatnt char
    char *p2;         //normal pointer to a char

    now which one of the following assignments are valid?
    p1=&b; //p1 assigned the address of a constatnt char...OK
    p1=&a; //p1 assigned the address of a char...OK
    p2=&a; //p2 assigned the address of a char...OK
    p2=&b; //p2 assigned the address of a constant char...FAIL
    the reasons is clear enough. you cannot assign a pointer to a char to point to a constant char. you can cast to do that but if p2 then were uesed to modify  that object then you might run into run time error.
    now imagine next assignments:
    *p1=5;  //FAIL...p1 points to constant char
    *p2=5;  //OK...p2 points to non constant char
    p1=p2;  //OK...p1 assigned address of pointer to char
    p2=p1;  //FAIL...cannot assign address of a pointer to constant char to p2.

    now more scary one:

    const char c='@';                //constant char
    const char *const ptr = &c;  //constant pointer to a constant char

    the longer the definition doesn't mean the more complicated though. 'const' keyword simply means constant value...dah, genius...second definition simply means neither the pointer nor the data it points to may be changed. Overall. it's programmer responsibility to check for potential inconsistencies.
    Good luck

    • 2013-05-05 08:39:06Z
    • Root Comment : 0 Sub Comment : 0
    • Visited : 2
    • Send Comment