SDL icon indicating copy to clipboard operation
SDL copied to clipboard

Added SDL_NUM_BUTTONS

Open CobaltXII opened this issue 1 year ago • 4 comments

In SDL_scancode.h, we have SDL_NUM_SCANCODES which is very useful when needing to store a copy of keyboard state, as we can use this constant for the array size. Similarly, many applications require to store the state of each mouse button in an array (I have done this to track the mouse state of the previous frame many times). However we must hardcode the size (6).

A better solution is to add this macro, and then one could simply write bool buttons[SDL_NUM_BUTTONS]; instead, which allows for extensibility of number of mouse buttons without breaking applications which would hardcode the constant 6.

It would be nice to see this added in SDL3, as I have found myself looking up the max value in SDL_mouse.h multiple times over the years. Thank you.

CobaltXII avatar Jul 16 '23 03:07 CobaltXII

With your proposal you'll get an invalid memory access if you try to write if (buttons[SDL_BUTTON_X2]) ...

slouken avatar Feb 08 '24 00:02 slouken

With your proposal you'll get an invalid memory access if you try to write if (buttons[SDL_BUTTON_X2]) ...

Yes, in my original proposal I had SDL_NUM_BUTTONS defined as 5. I updated that in commit Fix SDL_NUM_BUTTONS to be defined as 6. This should now be adequate as SDL_BUTTON_X2 is defined as 5.

CobaltXII avatar Feb 08 '24 20:02 CobaltXII

Is the number of mouse buttons supported by SDL actually limited to a certain number like that? I thought it supported arbitrary button numbers as long as the OS, mouse driver, and mouse hardware reported them - so the SDL_BUTTON_* macros are just there for convenience.

slime73 avatar Feb 08 '24 20:02 slime73

Is there a reason the SDL_BUTTON_* macro's don't start from 0?

madebr avatar Feb 08 '24 20:02 madebr

Is there a reason the SDL_BUTTON_* macro's don't start from 0?

Yes, so that 0 is an invalid button.

slouken avatar Mar 10 '24 16:03 slouken

I'll go ahead and close this, I think it would cause more programming errors than it solves, unfortunately.

slouken avatar Mar 10 '24 16:03 slouken