0

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?

Rogério Dec
  • 801
  • 8
  • 31
  • 1
    does getSize() return an unsigned value? try `- (int)window.getSize().y` to cast the value to a signed integer before negating it. – jdigital May 13 '18 at 01:00
  • It worked, thanks. Why this? If could explain in the answer block, I can close this question. – Rogério Dec May 13 '18 at 01:05
  • 1
    Unsigned types cannot represent negative values. Negating an `unsigned` is specified by the standards to use modulo arithmetic, so `-1` gives the maximum value that type can represent. Converting to a signed type before negating allows negative values to be represented. – Peter May 13 '18 at 01:09
  • `y` is an integer, not a class – M.M May 13 '18 at 01:16
  • Now I understand. In fact 'y' is an unsigned integer, which explain this behaviour. Thank you all. – Rogério Dec May 13 '18 at 01:21
  • my initial comment above was not quite accurate, so rewriting this as an answer below. – jdigital May 13 '18 at 01:55

2 Answers2

1

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.

Kevin DiTraglia
  • 25,746
  • 19
  • 92
  • 138
  • Not exactly "flip all the bits" - he probably isn't working on a 1's complement machine - but close ... – davidbak May 13 '18 at 01:55
  • @davidbak yeah was debating how specific i wanted to get and didn't end in a good place, just made it more vague =/ – Kevin DiTraglia May 13 '18 at 01:58
  • No problem. Just remember: No matter what you say on the internet you can always find someone more pedantic than you are yourself. – davidbak May 13 '18 at 02:27
1

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.

jdigital
  • 11,926
  • 4
  • 34
  • 51
  • 2
    This could cause undefined behavior. You need to use a singed type that is larger than the type of `sf::window.getSize().y` – NathanOliver May 13 '18 at 01:57