jagguy wrote:
if it is a constant then this shouldn't work but it odes
char *p ;
p="xbbat";
cout << p <<endl;
p="xbbat";
cout << p <<endl;
Which line are you saying shouldn't work? If you think that you
shouldn't be able to put the address of a static string constant into a
variable of type char*, see Bo's post about the historically-derived
exception for this case. However, based on the code snippet you
posted, I surmise that perhaps you're confused as to the different
kinds of constness, and what exactly is and isn't const in this case.
First of all, make sure you know the difference (or lack thereof)
between these types:
- char *
- const char *
- char const *
- char * const
- char const * const
- const char * const
The FAQ at
http://www.parashift.com/c++-faq-lit....html#faq-18.5
should help with this. Note that some of the above are equivalent.
In light of these distinctions, the snippet you posted should work fine
because the string literal is (in terms of operator=()) char const*
const, and p is of type char *. Ordinarily you can't assign from char
const* const to char *, but there's an exception for string literals,
as was mentioned. The second assignment statement, which I guess is
what you thought shouldn't work because of constness, is fine because
the left-hand side (p) is a non-const type: char*. The fact that you
once assigned to it from a const value doesn't change that -- const has
an infectuousness to it, but it doesn't work that way.
Luke