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

470 Views Asked by At

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?

2

There are 2 best solutions below

1
jdigital On BEST ANSWER

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.

3
Kevin DiTraglia On

As others have said in comments window size is stored as an unsigned integer, so the operation to take the negative of it ends up just creating a really big positive number.