"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Are `char`, `signed char`, and `unsigned char` Truly Distinct in C++?

Are `char`, `signed char`, and `unsigned char` Truly Distinct in C++?

Published on 2024-11-05
Browse:900

  Are `char`, `signed char`, and `unsigned char` Truly Distinct in C  ?

Character Types in C : Distinct or Equivalent?

In C , the behavior of character types (char) can sometimes differ from that of signed and unsigned integers, leading to confusion. Specifically, the following code demonstrates this difference:

#include 

typedef   signed char       int8;
typedef unsigned char      uint8;

struct TrueType {};
struct FalseType {};

template 
struct isX
{
   typedef typename T::ikIsX ikIsX;
};

template             struct isX  { typedef FalseType ikIsX; };
template             struct isX  { typedef FalseType ikIsX; };
template             struct isX  { typedef FalseType ikIsX; };

template  bool getIsTrue();
template            bool getIsTrue() { return true; }
template            bool getIsTrue() { return false; }

int main(int, char **t )
{
   cout ::ikIsX  >() ::ikIsX  >() ::ikIsX  >() 

This code compiles but produces different results for char than for int8 and uint8. This is because C treats char, signed char, and unsigned char as three distinct types.

In contrast, int and uint32 are equivalent types:

template             struct isX  { typedef FalseType ikIsX; };
template             struct isX  { typedef FalseType ikIsX; };

This distinction stems from the fact that char has historically been used for both representing characters and storing numeric values. As a result, C maintains backward compatibility by treating plain char as a separate type, distinct from int.

To determine which of the two representations char uses, the implementation-defined typedef char_traits::signed is provided. If this is true, char behaves as a signed type; otherwise, it behaves as an unsigned type.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3