On 8/21/2012 7:43 AM,
wrote:
> On Wednesday, December 2, 2009 6:09:57 PM UTC+5:30, thomas wrote:
>> void doit(const char* p){
>> char *q = p; //ERROR! <1>
>> }
>> char *p = "abc"; <2>
>> -------------------------------------------
>>
>> I think both <1> and <2> assign "const char *" to "char *".
>> But only <1> causes compile error. Why is <2> legal?
>
> please correct it to
> void doit(const char *p){
> char *q=strdup(p);
> }
> char *p=strdup("abc");
> These will work in new versions.
> compiler version 5.0 is not giving error in old one
> you specified.
You didn't answer the question, though. Try to pay attention.
To the OP:
It's legal because the Standard says it's legal. So, why does the
Standard say that? Because of the legacy issues. Once upon a time
there were no constant data in C. So, plenty of code was written like
<2>. So, when standardization was under way in C++ as well, it was
decided to keep the old C code legal in C++, so initialization of
pointers to non-const char was allowed to be done with string literals.
If you try to modify those characters, however, you get undefined
behavior (UB).
There are tools out there that would warn you about it, but it is NOT an
error to initialize a pointer to non-const char with a literal.
V
--
I do not respond to top-posted replies, please don't ask