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

  • 相关阅读:
    Python-发送邮件
    Python基础-类的继承
    Python基础-列表推导式
    三、Linux下mysql的完整安装
    二、linux下apache2.2.11+php5.6.3的环境配置
    linux下编译安装php各种报错大集合
    一、linux下nginx1.7.8+php5.6.3的环境配置
    linux ./configure 的参数详解
    div随窗口变化设置高度
    在地图上增加标注点并为每个点增加各自的信息窗口
  • 原文地址:https://www.cnblogs.com/hustxujinkang/p/4672413.html
Copyright © 2011-2022 走看看