gpt4 book ai didi

C: gcc 将 signed char 隐式转换为 unsigned char,反之亦然?

转载 作者:太空狗 更新时间:2023-10-29 16:53:35 25 4
gpt4 key购买 nike

我正在尝试学习 C,但目前遇到了数据类型大小的问题。

看看这段代码:

#include <stdio.h>
#include <limits.h>

int main() {
char a = 255;
char b = -128;
a = -128;
b = 255;
printf("size: %lu\n", sizeof(char));
printf("min: %d\n", CHAR_MIN);
printf("max: %d\n", CHAR_MAX);
}

printf 的输出是:

size: 1
min: -128
max: 127

这怎么可能? char 的大小是 1 字节,默认的 char 似乎是有符号的 (-128...127)。那么如何在不收到溢出警告的情况下分配大于 127 的值(当我尝试分配 -128 或 256 时收到警告)? gcc 是否自动转换为 unsigned char?然后,当我分配一个负值时,它会转换回来吗?它为什么这样做?我的意思是,所有这些含蓄并不会使它更容易理解。

编辑:

好的,它没有转换任何东西:

char a = 255;
char b = 128;
printf("%d\n", a); /* -1 */
printf("%d\n", b); /* -128 */

所以它从下往上开始计数。但是为什么编译器不给我警告呢?当我尝试分配 256 时,为什么会这样?

最佳答案

参见 the C99 Standard 中的 6.3.1.3/3

... 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.

因此,如果您没有收到信号(如果您的程序没有停止),请阅读编译器的文档以了解它的作用。


gcc 将行为(在 http://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html#Integers-implementation 中)记录为

  • The result of, or the signal raised by, converting an integer to a signed integer type when the value cannot be represented in an object of that type (C90 6.2.1.2, C99 6.3.1.3).

For conversion to a type of width N, the value is reduced modulo 2^N to be within range of the type; no signal is raised.

关于C: gcc 将 signed char 隐式转换为 unsigned char,反之亦然?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7268507/

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