I have 4 images that I would like to display, so I am using an unsigned short
to represent the index of the current image. When I press A, the index decreases by 1; When I press D, the index increases by 1.
I am calculating the index on the A keypress using image_index = (image_index - 1) % 4;
(and on the D keypress, image_index = (image_index + 1) % 4;
)
Everything works just as expected if I cycle thru going forwards (IE, pressing D), but if I am at index 0 and press A, it underflows to the max value of an unsigned short, and does not modulo by 4 to give me index 3.
I know that for signed types, that overflow/underflow is UB, but I was certain that for unsigned types it was well defined. Any ideas what might be causing it to ignore the modulo?
enum class Errors : short {
kSdlSuccess = 0,
kSdlInitFailure = -1,
kSdlWindowCreationError = -2,
kSdlRendererCreationError = -3
};
int main(int argc, char** argv) {
sdl::Context ctx;
sdl::Window window({ .w = 600, .h = 480, .flags = 0});
sdl::Renderer renderer(window, {0});
bool is_running {true};
unsigned short texture_index = 0;
SDL_Event event {};
while(is_running) {
while(SDL_PollEvent(&event)) {
if(event.type == SDL_QUIT) { is_running = false; }
else if(event.type == SDL_KEYDOWN) {
if(event.key.keysym.scancode == SDL_SCANCODE_A) { texture_index = (texture_index - 1) % 4; }
else if(event.key.keysym.scancode == SDL_SCANCODE_D) { texture_index = (texture_index + 1) % 4; }
}
}
printf("%d\n", texture_index);
renderer.setDrawColor(255, 0, 0, 255);
renderer.clearBuffer();
renderer.setDrawColor(0,0,0,255);
renderer.drawTexture(texture_index);
renderer.swapBuffer();
}
return static_cast<int>(Errors::kSdlSuccess);
}