I am making a game (for fun) and it has a scrolling screen. The following bit of code updates the position:
screen_x += screen_scroll_x;
if(screen_x < 0)
screen_x = 0;
if(screen_x > map_width - screen_width)
screen_x = map_width - screen_width;
I’m struggling to choose the correct integer type for screen_x. If it is signed, screen_x > map_width - screen_width induces a warning “comparison between unsigned and signed”. If it is unsigned, if(screen_x < 0) fails (with creative results) as screen_x can never be negative.
map_width is compared to the length of a string when loading the map and so if we make map_width signed the problem is shifted to that portion of code.
Many people have said that you should use the correct integer. They also say pay attention to your warnings and it bugs me that I do get warnings (get too many and you stop paying attention to them).
What would be the ideal solution?
You should not compare directly arbitrary
unsignedandsigned intsif you’re interested in mathematically sensible comparison. That’s because C(++)’s arithmetic is not your regular math arithmetic.In a C(++) expression involving a
signed intand anunsigned int, thesigned intis first converted to anunsigned intand then the operation is performed (+, *, <, etc).To correctly compare a
signed intand anunsigned intyou should take into account C(++)’s “arithmetic rules” and those type/value conversions mandated by the programming language and invisible to the eye of the uninitiated.So, you could compare the two like this:
As for using the right kind of integer, that’s a good advice, but sometimes one size doesn’t fit all. And on-screen coordinates is one such area, where it can be more than reasonable to have coordinates signed.
Imagine, for example, you want a routine to render a box on the screen and that you want to be able to draw a box moving across the screen, starting outside of the screen (moving into it) and ending outside (moving out).
If you choose the API like this:
the user of this function will have to do some extra math when drawing a portion of that box, when a part is on the screen and another is off the screen. All because there’s simply no way to tell the function that the original/uncropped box really isn’t all on the screen.
Now, if you choose this one instead:
and move that extra cropping math inside of the function, suddenly the user of this function is enabled to write very simple code. It could be as simple as: