Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't C++ accept signed or unsigned char for arrays of characters

Tags:

I am using C++ in native mode with Visual Studio 2017. That compiler compiles the statement below without complaint:

const char * AnArrayOfStrings[]  = {"z1y2x3w4", "Aname"};

However, if I change the above statement to specify that char is signed or unsigned, the compiler emits a C2440 error. For instance, the statements below, do not compile:

const signed   char * AnArrayOfStrings2[] = {"z1y2x3w4", "Aname"};

const unsigned char * AnArrayOfStrings2[] = {"z1y2x3w4", "Aname"};

I fail to see the reason for the compiler refusing to compile the statement when the sign of char is made explicit.

My question is: is there a good reason that I have failed to see for the compiler refusing to compile those statements ?

Thank you for your help (I did research in StackOverflow, the C++ documentation, I used Google and, consulted about a dozen C/C++ books in an effort to find the answer myself but, a reason still eludes me.)

like image 743
ScienceAmateur Avatar asked Mar 07 '18 06:03

ScienceAmateur


People also ask

Can you have a signed char in C?

There's no dedicated "character type" in C language. 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.

Does C default to signed or unsigned?

An int type in C, C++, and C# is signed by default. If negative numbers are involved, the int must be signed; an unsigned int cannot represent a negative number.

What are signed and unsigned characters in C?

Both of the Signed and Unsigned char, they are of 8-bits. So for signed char it can store value from -128 to +127, and the unsigned char will store 0 to 255. The basic ASCII values are in range 0 to 127. The rest part of the ASCII is known as extended ASCII.

Why do we need signed and unsigned char What is the difference in the range of the two and how is the range derived?

An unsigned type can only represent postive values (and zero) where as a signed type can represent both positive and negative values (and zero). In the case of a 8-bit char this means that an unsigned char variable can hold a value in the range 0 to 255 while a signed char has the range -128 to 127.


1 Answers

"z1y2x3w4" is const char[9] and there is no implicit conversion from const char* to const signed char*.

You could use reinterpret_cast

const signed char * AnArrayOfStrings[]  = {reinterpret_cast<const signed char *>("z1y2x3w4"),
                                           reinterpret_cast<const signed char *>("Aname")};
like image 136
Gaurav Sehgal Avatar answered Oct 25 '22 11:10

Gaurav Sehgal