Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion from char* to signed char*

Tags:

c++

char

signed

I saw a piece of valid C code I tried to compile as C++ and I got an error I can't understand.

char* t;
signed char* v = t;

error: invalid conversion from char* to signed char*

From what I learned, char and signed char are semantically identical, but are still considered as different by the compiler.

I know that the error is caused by the difference between these two type, my question is: Why does this difference exists ?

As far as I know char is implemented either as a signed char or as a unsigned char so it should be identical to either one or the other.


I consulted this question and it doesn't answer the point I want to know.

like image 738
Geoffroy Avatar asked Oct 18 '13 08:10

Geoffroy


People also ask

What is unsigned char * in C?

unsigned char is a character datatype where the variable consumes all the 8 bits of the memory and there is no sign bit (which is there in signed char). So it means that the range of unsigned char data type ranges from 0 to 255.

Is char the same as signed char?

ANSWER. There is a difference between a plain char and a signed char. By default, a plain char represents an unsigned char value.

Can I cast unsigned char to char?

Therefore, accessing a signed char (or char ) through an unsigned char* (or char ) and vice versa is not disallowed by this rule – you should be able to do this without problems.

Is there signed char?

char is an integer type, same (in that regard) as int , short and other integer types. char just happens to be the smallest integer type. So, just like any other integer type, it can be signed or unsigned.


1 Answers

Actually I finally found the spec part talking about this:

3.9.1 Fundamental types

  1. Objects declared as characters (char) shall be large enough to store any member of the implementation’s basic character set. If a character from this set is stored in a character object, the integral value of that character object is equal to the value of the single character literal form of that character. It is implementation-defined whether a char object can hold negative values. Characters can be explicitly declared unsigned or signed. Plain char, signed char, and unsigned char are three distinct types. A char, a signed char, and an unsigned char occupy the same amount of storage and have the same alignment requirements (3.11); that is, they have the same object representation. For character types, all bits of the object representation participate in the value representation. For unsigned character types, all possible bit patterns of the value representation represent numbers. These requirements do not hold for other types. In any particular implementation, a plain char object can take on either the same values as a signed char or an unsigned char; which one is implementation-defined.
like image 199
Geoffroy Avatar answered Oct 08 '22 05:10

Geoffroy