const is a promise to the compiler that you will not try to change the value using this label. You do it to protect yourself from your own mistakes.
For example:
1 2
char* x = "BeansOnToast";
x[0] = 'Z';
If you try to change any of the letters in that, you're asking for trouble, as it's forbidden (see "string literal"). A segFault is probably what you'll get when you run it (and when you compiled it, your compiler should have warned you).
1 2
constchar* x= "BeansOnToast";
x[0] = 'Z';
This simply won't compile, so you've made it impossible for yourself to cause that segFault.
While you can do this, this is considered as breaking the promise you made to the compiler. 'const' is a compile-time safety, but it allows the compiler to make assumptions and do things that can behave differently than non-const things.
char x[] = "BeansOnToast"; //Initialize x and memcpy "BeansOnToast"
x+13 = 'Z'; // Valid, but Out Of Bounds (Error writing to address error)
x[13] = 'Z'; // Same
instead, because you declared a new variable.
But we are talking about taking a constant's pointer.
1 2 3 4 5
char * x = "BeansOnToast"; // "BeansOnToast" is constant, and it should not be edited. So you should use 'const char *' to be sure it will never be edited.
x+13 = 'Z'; // SegFault / Out Of Bounds
x[13] = 'Z'; // Same thing.
x+1 = 'Z'; // SegFault
x[1] = 'Z'; // Same
x+13 = 'Z';
1. "x+13" returns a temporary pointer which points to a location 13 units away from x. You cannot assign to temporaries.
2. If you could assign to temporaries this code would do nothing, because you're making that temporary pointer point to something at memory address unsignedint('Z')...then doing nothing with it.
x+13 = 'Z';
1. "x+13" returns a temporary pointer which points to a location 13 units away from x. You cannot assign to temporaries.
2. If you could assign to temporaries this code would do nothing, because you're making that temporary pointer point to something at memory address unsigned int('Z')...then doing nothing with it.
Sure? I think it could be true if it was like this: ((&x)+13) = 'Z'
As x is a char*, it points to the first char, and adding 13 you get a pointer to the 13th char (not existing), but shouldn't it be valid? (I know what you mean)
What you just said is this code: ((&x)+13) = 'Z' (assign a character to a char **) (which is wrong)
What i am explaining you is this code: x+13 = 'Z' (assign a character to a char *) (which i think is good)
I am probably failing to express myself in the right way...
Or maybe i'm completely wrong.
EDIT: Or maybe it should be like: *(x+13) = 'Z'; Probably my fault then, sorry, LOL.
Yes, "*(x+13)" is a reference to a char, and you can easily assign to that. That doesn't mean it won't segfault as discussed above, but it's legal syntax ;)