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只是为了得到一个相应大小的整数型数据而已!

  • 相关阅读:
    图像切割之(五)活动轮廓模型之Snake模型简单介绍
    拓扑排序的原理及事实上现
    理解class.forName()
    Java中StringBuilder的清空方法比較
    Java实现BASE64编解码
    KMP算法具体解释(贴链接)
    基于PCM2912a的USB声卡设计
    51. 腾讯面试题:一个二叉树,中序遍历,找一个节点的后一个节点
    Handler和HandlerThread
    Nuget-QRCode:jquery-qrcode
  • 原文地址:https://www.cnblogs.com/hustxujinkang/p/4672413.html
Copyright © 2011-2022 走看看