Difference between char and signed char in c++?

后端 未结 4 2151
小蘑菇
小蘑菇 2020-12-15 03:19

Consider the following code :

#include 
#include 

int main(int argc, char* argv[])
{
    std::cout<<\"std::is_same&         


        
4条回答
  •  我在风中等你
    2020-12-15 03:58

    There are three distinct basic character types: char, signed char and unsigned char. Although there are three character types, there are only two representations: signed and unsigned. The (plain)char uses one of these representations. Which of the other two character representations is equivalent to char depends on the compiler.

    In an unsigned type, all the bits represent the value. For example, an 8-bit unsigned char can hold the values from 0 through 255 inclusive.

    The standard does not define how signed types are represented, but does specify that the range should be evenly divided between positive and negative values. Hence an 8-bit signed char is guaranteed to be able to hold values from -127 through 127.


    So how to decide which Type to use?

    Computations using char are usually problematic. Char is by default signed on some machines and unsigned on others. So we should not use (plain)char in arithmetic expressions. Use it only to hold characters. If you need a tiny integer, explicitly specify either signed char or unsigned char.

提交回复
热议问题