开发者

Pointer arithmetic and const qualifier in C

In the following p开发者_运维技巧iece of code, to calculate strlen,

int s(const char* str)
{   
    int count=0;        
    while(*str++) count++;
    return count;
}

You can see that the argument str is const. But, the compiler does not complain when I do a str++. My question is

When passing pointers as arguments to a C function, if is is qualified with const, How can I still perform pointer arithmetic on it? What is const in the above function?


const char* str;

means a non-const pointer to a const data.

char* const str;

means a const pointer to a non-const data.

const char* const str;

means a const pointer to a const data.

The reason for this is that in C++ the variable type declarations are parsed from right to left, which results in that the word "const" always defines the constness of the thing that it's closest to.


It's not declaring the pointer const, it's declaring the thing pointed to as const. Try this:

int s(const char* const str)

With this declaration, you should get a compile error when you modify str.


const char * ch; // non-const pointer to const data
char * const ch; // const pointer to non-constant data.

const char * const ch; // const pointer to const data

Note: Also

const char * ch;

equals to

char  const * ch;


The pointer points to a const char, a read-only character array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜