简体   繁体   中英

Pointer arithmetic and const qualifier in C

In the following piece 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;

指针指向一个const char ,一个只读字符数组。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM