0

I have a strange situation with the C++ compiler of Visual Studio 2012.

This is merely a test code, which should fail:

char s1[5] = "new";
char s2[5] = "old";
char const* p = s1;   
p++;                  // should fail
p = s2;               // this line should also fail;

Can someone tell me, why it works?

3 Answers 3

4

There's no reasons those lines should fail. Perhaps you are confusing char const* with char * const. In the first case, the chars are const. In the second, the pointer is const. In your code, since the pointer is not const, it's fine to do both p++ and p = s2;.

Remember the rule: “const applies to its left, unless there is nothing, in which case it applies to its right.”

Sign up to request clarification or add additional context in comments.

3 Comments

Are "char const* p = s1" and "const char* p = s1" identical ?
"char const x = 5" and "const char x = 5" too ?
@moller1111 Yes. Here you can read more about it. A bit too detailed but worth it. parashift.com/c++-faq/const-correctness.html
2
const int x;      // constant int
x = 2;            // illegal - can't modify x

const int* pX;    // changeable pointer to constant int
*pX = 3;          // illegal -  can't use pX to modify an int
pX = &someOtherIntVar;      // legal - pX can point somewhere else

int* const pY;              // constant pointer to changeable int
*pY = 4;                    // legal - can use pY to modify an int
pY = &someOtherIntVar;      // illegal - can't make pY point anywhere else

const int* const pZ;        // const pointer to const int
*pZ = 5;                    // illegal - can't use pZ to modify an int
pZ = &someOtherIntVar;      // illegal - can't make pZ point anywhere else

PS: I blatantly copied this from here , I think having it here as well will be useful somewhere in the future.

Comments

2

You are thinking that the incrementation should not work because it is const char*. However the const here specifies that what is pointed to can not be modified. Not that the pointer can be modified.

However this is illegal.

char s1[5] = "new";
char s2[5] = "old";
char const* const p = s1;
            ^^^^   
p++;                  // should not compile
p = s2; 

C++ const qualifier applies to what is on left of it, if there is something on the left. otherwise it applies to what is on the right.

Read Here for more info about const correctness.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.