1
char* s1 = new char[30];
char s2[] = "is not";
const char* s3 = "likes";
s3 = "allows";
strcpy( s2, s3 );
sprintf( s1, "%s %s %s using functions.", "C++", s2, "fast code" );
printf( "String was : %s\n", s1 );
delete[] s1;

I was confused at the

const char* s3 = "likes";
s3 = "allows";

Because I think s3 is a const, so it cannot alter. However, when s3 = "allows" it works. Why?

Pai
  • 327
  • 1
  • 3
  • 10
  • [This answer might help](http://stackoverflow.com/questions/7736049/const-char-pointer-assignments/7738315#7738315) – Ed Heal May 21 '16 at 11:28

1 Answers1

5

I think s3 is a const

No, s3 is not const itself, it's pointer to const, so s3 = "allows"; is fine, and *s3 = 'n'; will fail instead.

If you meant const pointer, char* const s3 and const char* const s3 are both const pointer, and then s3 = "allows"; will fail.

Summary (note the position of const)

char* s3 is non-const pointer to non-const, both s3 = "allows"; and *s3 = 'n'; are fine.
const char* s3 is non-const pointer to const, s3 = "allows"; is fine and *s3 = 'n'; fails.
char* const s3 is const pointer to non-const, s3 = "allows"; fails and *s3 = 'n'; is fine.
const char* const s3 is const pointer to const, both s3 = "allows"; and *s3 = 'n'; will fail.

See Constness of pointer.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405