其他分享
首页 > 其他分享> > c – int8_t和uint8_t是char类型吗?

c – int8_t和uint8_t是char类型吗?

作者:互联网

鉴于这个C 11计划,我应该期待看到一个数字还是一个字母?还是没有期望?

#include <cstdint>
#include <iostream>

int main()
{
    int8_t i = 65;
    std::cout << i;
}

标准是否指定此类型是否可以是字符类型?

解决方法:

根据C 0x FDIS(N3290)的§18.4.1[cstdint.syn],int8_t是一个可选的typedef,其指定如下:

namespace std {
  typedef signed integer type int8_t;  // optional
  //...
} // namespace std

§3.9.1[basic.fundamental]陈述:

There are five standard signed integer types: “signed char”, “short int”, “int”, “long int”, and “long long int”. In this list, each type provides at least as much storage as those preceding it in the list. There may also be implementation-defined extended signed integer types. The standard and extended signed integer types are collectively called signed integer types.

Types bool, char, char16_t, char32_t, wchar_t, and the signed and unsigned integer types are collectively called integral types. A synonym for integral type is integer type.

§3.9.1还规定:

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.

很有可能得出结论,int8_t可能是char的typedef,前提是char对象采用有符号值;但是,情况并非如此,因为char不在有符号整数类型列表中(标准和可能扩展的有符号整数类型).另请参见std :: make_unsigned和std :: make_signed上的Stephan T. Lavavej’s comments.

因此,int8_t是signed char的typedef,或者是扩展的有符号整数类型,其对象恰好占用8位存储.

但是,要回答你的问题,你不应该做出假设.因为已经定义了x.operator<<(y)和operator<<(x,y)两种形式的函数,§13.5.3[over.binary]说我们参考§13.3.1.2[over.match] .oper]确定std :: cout<<的解释一世. §13.3.1.2反过来说,实现根据§13.3.2和§13.3.3从候选函数集中选择.然后我们查看§13.3.3.2[over.ics.rank]来确定:
>模板< class traits> basic_ostream&LT炭,性状&GT&安培;如果int8_t是签名字符的完全匹配(即signed char的typedef),则将调用operator<(basic_ostream< char,traits>&,signed char)模板.
>否则,int8_t将被提升为int和basic_ostream< charT,traits>&将调用operator<(lt;(int n)成员函数.
在std :: cout<<的情况下你对你的uint8_t对象:
>模板< class traits> basic_ostream&LT炭,性状&GT&安培;如果uint8_t是unsigned char的完全匹配,则将调用operator<(basic_ostream< char,traits>&,unsigned char)模板.
>否则,因为int可以表示所有uint8_t值,uint8_t将被提升为int和basic_ostream< charT,traits>&将调用operator<(lt;(int n)成员函数.
如果您总是想要打印一个角色,最安全,最明确的选择是:

std::cout << static_cast<signed char>(i);

如果你总想打印一个数字:

std::cout << static_cast<int>(i);

标签:c,c11,language-lawyer,iostream,standard-library
来源: https://codeday.me/bug/20190923/1813451.html