const的位置決定修飾的對像,如 char const *p表示修飾的是*p,所以不能用*p='a',而p這個address是可以修改的,比如p=&q。

如果是char* const p,則表示修飾的是p這個address。所以可以用*p='a',而不能p=&q。這兩個是相反的例子。

再來是都不能修改的狀況,const char* const p,則*p跟p都不能再賦值了。

最後const是左修飾,所以 const char跟 char const是一樣的意思。

範例如下:

#include <stdio.h>

int main()
{
        char c1='a';
        char c2='b';
        const char *a=&c1;
        a=&c2;
        *a='c';  //error: assignment of read-only location ‘*a’
        printf("a is %c\n",*a);

        char* const b=&c1;
        *b='e';
        b=&c2;//error: assignment of read-only variable ‘b’
        printf("b is %c\n",*b);
        
        const char*  const c=&c1;
        c=&c2;//error: assignment of read-only variable ‘c’
        *c='f'; //error: assignment of read-only variable ‘*c’
        return 0 ;

}


arrow
arrow
    全站熱搜

    kezeodsnx 發表在 痞客邦 留言(0) 人氣()