gpt4 book ai didi

c,unsigned char 和 char 上的相等运算符

转载 作者:太空宇宙 更新时间:2023-11-04 06:15:45 25 4
gpt4 key购买 nike

当我将 intunsigned int 进行比较时,为什么我可以得到 "x==y"

那么,为什么当我比较charunsigned char时,我得到的是"a!=b",虽然它们确实有相同的位模式“0xff

在应用相等运算符时,是否考虑变量类型?

代码:

#include <stdio.h>

int main()
{
unsigned int x = 0xFFFFFFFF;
int y = 0xFFFFFFFF;
printf("unsigned int x = 0xFFFFFFFF;\n");
printf("int y = 0xFFFFFFFF;\n");
if (x < 0)
printf("x < 0\n");
else
printf("x > 0\n");
if (y < 0)
printf("y < 0\n");
else
printf("y > 0\n");
if(x==y)
printf("x==y\n\n");
///////////-- char --////////////////////////
unsigned char a = 0xFF;
char b = 0xFF;
printf("unsigned char a = 0xFF\n");
printf("char b = 0xFF\n");
if (a < 0)
printf("a < 0\n");
else
printf("a > 0\n");
if (b < 0)
printf("b < 0\n");
else
printf("b > 0\n");
if(a==b)
printf("a==b\n");
else
printf("a!=b\n");

}

输出:

unsigned int x = 0xFFFFFFFF;
int y = 0xFFFFFFFF;
x > 0
y < 0
x==y

unsigned char a = 0xFF
char b = 0xFF
a > 0
b < 0
a!=b

最佳答案

来自 C11 ISO/IEC 9899:201x 标准:

Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.

在与 unsigned int x = 0xFFFFFFFF 比较之前,提升应用于 int y = 0xFFFFFFFF。将 int y 提升为 unsigned int 将保留值 0xFFFFFFFF,这会导致 x == y

另一方面:

If an int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int ; otherwise, it is converted to an unsigned int . These are called the integer promotions . All other types are unchanged by the integer promotions. The integer promotions preserve value including sign. As discussed earlier, whether a ‘‘plain’’ char is treated as signed is implementation-defined.

这意味着 unsigned char a = 0xFFchar b = 0xFF 在比较之前都被转换为 signed int。但是转换 b 会导致符号扩展,这意味着 b 的值被扩展为 0xFFFFFFFF == -1 导致 int a = 255 大于 int b = -1

关于c,unsigned char 和 char 上的相等运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46290986/

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