C语言uint8_t和char的区别,c – int8_t和uint8_t是char类型吗?

本文探讨了C语言中uint8_t和int8_t与char类型的区别。尽管int8_t可能是signed char的typedef,但char并不属于有符号整数类型列表。在打印int8_t或uint8_t时,不应假设其行为,而应使用static_cast确保正确输出数值或字符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

#include

#include

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<

>模板< class traits> basic_ostream&LT炭,性状&GT&安培;如果int8_t是签名字符的完全匹配(即signed char的typedef),则将调用operator&,signed char)模板.

>否则,int8_t将被提升为int和basic_ostream< charT,traits>&将调用operator

在std :: cout<

>模板< class traits> basic_ostream&LT炭,性状&GT&安培;如果uint8_t是unsigned char的完全匹配,则将调用operator&,unsigned char)模板.

>否则,因为int可以表示所有uint8_t值,uint8_t将被提升为int和basic_ostream< charT,traits>&将调用operator

如果您总是想要打印一个角色,最安全,最明确的选择是:

std::cout << static_cast(i);

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

std::cout << static_cast(i);

标签:c,c11,language-lawyer,iostream,standard-library

来源: https://codeday.me/bug/20190923/1813451.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值