-4
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 is a pointer. The const means that the pointer cannot be modified. But in the for loop, there is ++p, which means the pointer is being iterated over/incremented to access the values *p

There’s a contradiction there - p cannot be modified yet it is being incremented/modified?

melpomene
  • 84,125
  • 8
  • 85
  • 148
user3180
  • 1,369
  • 1
  • 21
  • 38
  • 1
    No, the `const` means the thing pointer at can't be modified. You can still change the pointer. – Galik Sep 24 '18 at 01:17
  • 2
    That const means that what `p` points to is const, not `p` itself. The const would need to be on the other side of the `*` for what you describe. – Retired Ninja Sep 24 '18 at 01:18
  • @mrunion no, it does not. – Swordfish Sep 24 '18 at 01:22
  • @Swodrfish -- yes you are correct. I had misstated the reason and removed my post as it was incorrect. Thanks! – Matt Runion Sep 24 '18 at 01:25
  • 1
    I wonder why you felt it necessary to include Stroustrup's name in your question.. – user3738870 Sep 24 '18 at 01:34
  • Also see [What is the difference between char * const and const char *?](https://stackoverflow.com/q/890535/608639), [constant pointer vs pointer on a constant value](https://stackoverflow.com/q/10091825/608639) and friends. – jww Sep 24 '18 at 01:35
  • 1
    @user3738870 The code is from *A Tour of C++* by Stroustrup. – melpomene Sep 24 '18 at 01:38
  • @malpomene Thanks, so it basically denotes the author of the code in question right? – user3738870 Sep 24 '18 at 01:40

1 Answers1

2

Declarations in C++ are read from right to left. So something like

const char* p

would read: p is a non-const pointer to a const char.

Evidently, p is not const, but what it points to is const. So *p = 's' is illegal, but p++ is not.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
DeiDei
  • 10,205
  • 6
  • 55
  • 80