将无符号整数变量转换为有符号变量

标签 c unsigned signed

为什么下面的程序输出b 大于a? 即使 b 包含 -2。

void main()
{
    unsigned int a=12;
    int b=-2;

    if(a>b)
        printf("a is greater");
    else
        printf("b is greater");

    getch();
}

最佳答案

首先引用关系运算符的C11标准,第6.5.8章

If both of the operands have arithmetic type, the usual arithmetic conversions are performed.

现在,按照第 6.3.1.8 章常规算术转换中的描述,如果您尝试在signedunsigned 之间执行算术运算code> 整数(类型),signed 将被提升为 unsigned 类型(更高级别),然后操作将发生。

所以,在这里,为了进行比较,b 的值被转换为 unsigned 类型,您得到的是错误输出那里。

引用同一章节的相关部分

[...] Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.

您还可以查看通常的算术提升规则 here

也就是说,void main() 应该是 int main(int argc, char* argv[]),或者至少是 int main(无效)

关于将无符号整数变量转换为有符号变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32867000/

相关文章:

c++ - 位集和有符号值

c - 如何检测 C 中有符号整数的编码?

c++ - 为什么这个 if 条件无法比较负整数和正整数

c - 无法理解 C 中 union 程序的输出

java - 代表 C 左移有符号字符与 Java 中的无符号字符

c - 如何输入1000位整数

c - 算术运算期间的数据类型提升 : -1 < (unsinged int) 1 == false

c - 有符号整数和无符号整数是一一对应的吗?

c - 这段代码中的 XS 内存泄漏?

c - 警告 : incompatible implicit declaration of built-in function 'lrint'