zoukankan      html  css  js  c++  java
  • char, signed char, and unsigned char in C++

    关于这三者的区别stackoverrflow里有一个答案是这样说的:

    3.9.1 Fundamental types [basic.fundamental]

    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 (basic.types); 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.

    首先要明确的是,他们是三种不同的类型:

      在VS2013的STL库实现里面,有这样的代码:

     

    inline void _Fill(char *_First, char *_Last, char _Val)
        {    // copy char _Val through [_First, _Last)
        _CSTD memset(_First, _Val, _Last - _First);
        }
    
    inline void _Fill(signed char *_First, signed char *_Last, signed char _Val)
        {    // copy signed char _Val through [_First, _Last)
        _CSTD memset(_First, _Val, _Last - _First);
        }
    
    inline void _Fill(unsigned char *_First, unsigned char *_Last, unsigned char _Val)
        {    // copy unsigned char _Val through [_First, _Last)
        _CSTD memset(_First, _Val, _Last - _First);
        }

    可以看到,写了三个重载函数,分别针对这三种类型。

    其次,他们占用的内存是一样的:

      在C/C++里面用sizeof运算符的时候,得到的大小是以一个char为基本单位的,也就是说无论采用哪种实现,对这三种类型得到的结果都是1.

    最后:

      对于字符串表示,毫无疑问应该用char,标准并不限定这个char是有符号还是无符号的。至于signed char、unsigned char只是为了得到一个相应大小的整数型数据而已!

  • 相关阅读:
    java基础-基本的输入与输出
    Java基础-位运算符Bitwise Operators
    Java基础-字符串连接运算符String link operator
    Java基础-赋值运算符Assignment Operators与条件运算符Condition Operators
    Java基础-逻辑运算符Logic Operators
    Java基础-比较运算符Compare Operators
    Java基础-算术运算符(Arithmetic Operators)
    NGUI裁剪模型和粒子
    编辑器插件数据保存之Serializable
    using语法糖
  • 原文地址:https://www.cnblogs.com/hustxujinkang/p/4672413.html
Copyright © 2011-2022 走看看