c - 为什么C语言中每一个signed int类型都必须有一个对应的unsigned int类型?

标签 c c99 unsigned signed stdint

我在阅读 C in a Nutshell 时发现了这个:

"If an optional signed type (without the prefix u) is defined, then the corresponding unsigned type (with the initial u) is required, and vice versa."

该段落是关于具有精确宽度的整数类型(C99)

最佳答案

因为 C 的原始数据类型带有有符号和无符号版本。从 C99 的基本原理,他们解释了 inttypes/stdint 的必要性。像这样的类型,C99 基本原理 V5.10 7.8:

C89 specifies that the language should support four signed and unsigned integer data types, char, short, int and long, but places very little requirement on their size other than that int and short be at least 16 bits and long be at least as long as int and not smaller than 32 bits. For 16-bit systems, most implementations assign 8, 16, 16 and 32 bits to char, short, int, and long, respectively. For 32-bit systems, the common practice is to assign 8, 16, 32 and 32 bits to these types. This difference in int size can create some problems for users who migrate from one system to another which assigns different sizes to integer types, because Standard C’s integer promotion rule can produce silent changes unexpectedly. The need for defining an extended integer type increased with the introduction of 64-bit systems.

The purpose of <inttypes.h> is to provide a set of integer types whose definitions are consistent across machines and independent of operating systems and other implementation idiosyncrasies. It defines, via typedef, integer types of various sizes. Implementations are free to typedef them as Standard C integer types or extensions that they support. Consistent use of this header will greatly increase the portability of a user’s program across platforms.

本意是执行inttypes/stdin可以用 typedef 来执行.因此,需要有一种固定宽度类型对应于每种支持的原始数据类型。

至于为什么 C 首先有符号类型,那只是因为 CPU:s 支持有符号和无符号数字运算。但也因为我们希望使用整数类型来表示存储的原始二进制数据:类型 unsigned char/uint8_t是 C 语言,相当于一个字节的原始数据,可以包含任何内容。 (这就是字符类型不能包含任何陷阱表示等的原因)

从 C99 标准本身,我们可以找到与您的书 C99 6.2.5/6 中类似的文本:

For each of the signed integer types, there is a corresponding (but different) unsigned integer type (designated with the keyword unsigned) that uses the same amount of storage (including sign information) and has the same alignment requirements.

关于c - 为什么C语言中每一个signed int类型都必须有一个对应的unsigned int类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48523060/

相关文章:

c - 如何在 C 中将端口设置为按钮的输入?

c - 如何防止 for 循环的最后一个循环中打印空格

c - clang c99 中的主要函数

java - Java 字节数组中的无符号字节

python - 关于 C 溢出,如何在 Python 中使用 64 位无符号整数数学?

c - 如何在字符串末尾添加一个字符

python - 如何使用 python 编写可以在 c 中读取的二进制结构?

C - Eclipse - "Mixed"方言和 ANSI 支持崩溃程序吗?

c - 传递多维数组

c - 如何在 C 中将无符号定义变量转换为有符号定义变量