天天看點

C語言uint8_t和char的差別,c – int8_t和uint8_t是char類型嗎?

鑒于這個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