cundefined-behaviorinteger-overflow

Find a value y such (x < y) == (-x > -y) will be false, when x is a signed integer and x=1?


The question asks,

Let int x = 1, find a value for int y where the following statement will return false: (x < y) == (-x > -y)

I know the answer should be 4 bytes long (8 hex digits), but I don't know how to approach the question.


Solution

  • There isn't any value for y for which the expression is false. If we compile this:

    int test(int y)
    {
        int x = 1;
        
        return (x < y) == (-x > -y);
    }
    

    both gcc and clang with optimization enabled will generate this code:

    test(int):
            mov     eax, 1
            ret
    

    Any other answer that thinks is smart most likely uses overflow and is actually Undefined Behavior or misunderstands some C fundamentals.

    Actually there are no values for either x or y for which the expression is false:

    int test(int x, int y)
    {
        return (x < y) == (-x > -y);
    }
    

    gives the same:

    test(int, int):
            mov     eax, 1
            ret
    

    It seems some people miss the implication and significance of the fact that the compilers transform the expression into return 1. This is proof that the compiler has definitely proven that there is no valid input for which the expression is false. Otherwise it would not have been allowed to do this optimization.