I have tried compiling with gcc -Wall -pedantic-errors -std=c89
the following code:
int main(){
unsigned char a[] = "foo";
unsigned char *b= "foo";
unsigned char *c= ( unsigned char *) "foo";
return 0;
}
Why does the second initialization raise the error pointer targets in initialization differ in signedness
, but the other two declarations are allowed?
It seems that in the second case, implicit conversion from char *
to unsigned char *
is not done.
Technically, because the standard explicitly allows arrays of a (any) character type to be initializable with string literals (6.7.9p14):
An array of character type may be initialized by a character string literal or UTF-8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.
while for most pointers conversions, the standard requires explicit casts (6.5.4p3):
Conversions that involve pointers, other than where permitted by the constraints of 6.5.16.1, shall be specified by means of an explicit cast.
Intuitively, because you can do:
unsigned char a0 = 'f', a1 = 'o', a2 = 'o';
or in other words, because you can initialize an integer type with a different integer type without having to cast explicitly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With