首页 > 解决方案 > 常量指针 C++ Stroustrup

问题描述

int count_x(const char* p, char x)
     // count the number of occurrences of x in p[]
     // p is assumed to point to a zero-terminated array of char (or to nothing)
{
     if (p==nullptr)
           return 0;
     int count = 0;
     for (; *p!=0; ++p)
           if (*p==x)
                 ++count;
     return count;
}

p 是一个指针。const 意味着指针不能被修改。但是在for循环中,有++p,这意味着指针被迭代/递增以访问值*p

那里有一个矛盾 - p 不能被修改,但它正在被递增/修改?

标签: c++pointersconstants

解决方案


C++ 中的声明是从右到左读取的。所以像

const char* p

将阅读:p是一个非常量指针 a const char

显然,pis not const,但它指向的是const。所以*p = 's'是非法的,但p++不是。


推荐阅读