Re: const char assignments
LarryW wrote:
In article <fhho53phd5hsu711ndll0pef4mfl7fk522@4ax.com>, MrAsm wrote:
On Tue, 29 May 2007 08:14:33 PDT, LarryW <lwdaddio@newsgroups.nospam>
wrote:
const char * string = "A string";
const char * c_string;
const unsigned char * uc_string;
const signed char * sc_string;
c_string = string; // this works fine
uc_string = string; // error: can't assign "const char *" to "const
unsigned char *"
sc_string = string; // error: can't assign "const char *" to "const
signed char *"
Try casting:
uc_string = (const unsigned char *) string;
sc_string = (const signed char *) string;
MrAsm
Yes, I know that I can cast it away but I was wondering why I need to?
You don't, you just have to use the right datatype. Other than that, the
advise to cast in general and in C++ the advise to use C-style casts is
utter nonsense. For your own sake, don't do that.
Other than that, if Alex' explanation doesn't help, I'd offer another: In
the case of plain signed char vs unsigned char, you have simple integral
values that can be converted to each other. In the case of pointers, you
have the pointer value, which usually could be converted, and the stuff it
points to. Its the stuff it points to which would also have to be
converted, but that isn't feasible, after all the compiler can't know if
that memory was allocated using new/malloc or on the stack or as part of an
aggregate. Further, it wouldn't make sense either, because that would mean
that 'uc_string' and 'string' would modify different memory areas and
changes in one wouldn't be reflected in the other.
HTH
Uli