gpt4 book ai didi

c - 在 C 中打印声明的 char 值

转载 作者:太空宇宙 更新时间:2023-11-04 01:30:23 24 4
gpt4 key购买 nike

我知道字符变量的范围是(有符号)-128 到 127 和(无符号)0 到 255

char x;
x = 128;

printf("%d\n", x);

但是它是如何工作的呢?为什么我得到 -128 for x

最佳答案

printf 是一个可变参数函数,只为第一个参数提供确切的类型。
这意味着默认提升应用于以下参数,因此所有等级小于 int 的整数都被提升为 intunsigned int,并且等级较小的所有 float 值 double 都提升为 double

如果您的实现的 CHAR_BIT 为 8,并且简单的 char 已签名,并且您有一个强制性的 2s 补码实现,那么您将得到

128(文字)到 -128(char/signed char)到 -128(int)打印为 int => -128

如果满足所有列出的条件但强制性的 2s 补码实现,您将获得一个信号或一些实现定义的值。

否则你会得到 128 的输出,因为 128 适合 char/unsigned char

案例 2 的标准报价(感谢 Matt 的 unearthing the right reference ):

6.3.1.3 Signed and unsigned integers

1 When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
2 Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.60)
3 Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

关于c - 在 C 中打印声明的 char 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23691891/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com