找到一个值 y 这样 (x < y) == (-x > -y) 将是假的,当 x 是有符号整数并且 x=1 时?

scy*_*y17 0 c

问题问,

让 int x = 1,找到一个 int y 的值,其中以下语句将返回 false: (x < y) == (-x > -y)

我知道答案应该是 4 个字节长(8 个十六进制数字),但我不知道如何解决这个问题。

bol*_*lov 8

没有任何值y的表达式为假。如果我们编译这个:

int test(int y)
{
    int x = 1;
    
    return (x < y) == (-x > -y);
}
Run Code Online (Sandbox Code Playgroud)

启用优化的 gcc 和 clang 都会生成以下代码:

test(int):
        mov     eax, 1
        ret
Run Code Online (Sandbox Code Playgroud)

任何其他认为聪明的答案很可能使用溢出,实际上是未定义的行为或误解了一些 C 基础知识。

实际上,没有任何值xy表达式为假的值:

int test(int x, int y)
{
    return (x < y) == (-x > -y);
}
Run Code Online (Sandbox Code Playgroud)

给出相同的:

test(int, int):
        mov     eax, 1
        ret
Run Code Online (Sandbox Code Playgroud)

似乎有些人忽略了编译器将表达式转换为return 1. 这证明编译器已明确证明不存在表达式为假的有效输入。否则它不会被允许进行这种优化。

  • @mcleod_ideafix:`0x80000000`会导致[有符号溢出](https://en.wikipedia.org/wiki/Integer_overflow),从而导致[未定义的行为](https://en.wikipedia.org/wiki/Undefined_behavior )。 (6认同)