1
votes

I have a const char arr[] parameter that I am trying to iterate over,

char *ptr;
for (ptr= arr; *ptr!= '\0'; ptr++) 
  /* some code*/

I get an error: assignment discards qualifiers from pointer target type

Are const char [] handled differently than non-const?

4

4 Answers

11
votes

Switch the declaration of *ptr to be.

const char* ptr;

The problem is you are essentially assigning a const char* to a char*. This is a violation of const since you're going from a const to a non-const.

10
votes

As JaredPar said, change ptr's declaration to

const char* ptr;

And it should work. Although it looks surprising (how can you iterate a const pointer?), you're actually saying the pointed-to character is const, not the pointer itself. In fact, there are two different places you can apply const (and/or volatile) in a pointer declaration, with each of the 4 permutations having a slightly different meaning. Here are the options:

char* ptr;              // Both pointer & pointed-to value are non-const
const char* ptr;        // Pointed-to value is const, pointer is non-const 
char* const ptr;        // Pointed-to value is non-const, pointer is const
const char* const ptr;  // Both pointer & pointed-to value are const.

Somebody (I think Scott Meyers) said you should read pointer declarations inside out, i.e.:

const char* const ptr;

...would be read as "ptr is a constant pointer to a character that is constant".

Good luck!

Drew

0
votes

The const declaration grabs whatever is to the left. If there is nothing it looks right.

0
votes

For interation loops like the above where you don't care about the value returned you should say ++ptr rather than ptr++.

ptr++ means:

temp = *ptr;
++ptr;
return temp;`

++ptr means:

++ptr;
return *ptr;

For the primitive types, the compiler will apply this optimization but won't when iterating over C++ objects so you should get in the habit of writing it the right way.