Search code examples
c++classoperand

c++: Why minus signal in front of an integer gives a crazy number?


I'm using an integer from a SFML class to fetch the y coordinate of the current window:

sf::window.getSize().y

This brings for example the value:

300

But I want the negative value, so I put the minus sign in front:

- sf::window.getSize().y

Then I get this:

4294966696

Why does it happen?


Solution

  • sf::window.getSize().y is an unsigned value. Cast it to a signed value before negating it, for example:

    -(int)sf::window.getSize().y
    

    As to why this happens, the negation operation (most likely twos complement artithmetic) will flip the topmost bit, making the value look like a really large number instead of a negative number.

    @NathanOliver's comment below is correct. Converting from an unsigned value to a signed value basically loses one bit, so it would be safest to use a larger type. In practice, if you can guarantee that the resulting value is small enough to fit into the the signed type, then you can make your own choice about which signed type to use.