C语言比较两个不同符号的数会发生什么?

What happen when comparing two numbers of different sign in C language?

我在 fabien sanglard's website 上找到了这段代码。 我是 C 编程语言的新手,我需要很好地解释这段代码以及如何让 -1 大于 1。

unsigned int   ui_one       =  1 ;
signed   int   i_one        =  1 ;
signed   short s_minus_one  = -1 ;

if( s_minus_one > ui_one)
    printf("-1 > 1 \n");

if( s_minus_one < i_one) 
    printf("-1 < 1 \n");

#./run
#
# -1 > 1 
# -1 < 1

Usual arithmetic promotions (6.3.1.8)申请

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

并且在 if( s_minus_one > ui_one) 中,s_minus_one 被转换为 unsigned int

转换受制于 6.3.1.3p2:

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.

所以你的 (unsigned int)s_minus_one 会得到 UINT_MAX 并且 UINT_MAX 大于 ui_one

在 gcc 和 clang 上,您可以使用 -Wsign-compare -Wconversion(或使用 -Wextra)进行编译以获得有关这些转换的警告 (https://gcc.godbolt.org/z/dZ6L-y)。