Associating added and removed controllers

Using SDL2

I want to list connected controllers and open only one of (first) them, then when a controller is removed I want to remove that controller from the list. Also I dont want to open and listen for events for all controllers. 1 controller should be opened at most and my app will listen events of that controller.

The problem arises on SDL_CONTROLLERDEVICEREMOVED. Since I don’t open controllers except 1st one, event.cdevice.which gives an incrementing output, which I cannot relate with numbers I get on SDL_CONTROLLERDEVICEADDED.

There is a quite nice explaination regarding the meaning of event.cdevice.which on SDL_CONTROLLERDEVICEADDED and SDL_CONTROLLERDEVICEREMOVED events:

But since I don’t open every device connected, I can’t resolve the issue by using
SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(myController));

I’m looking for something to associate added and removed joysticks even when the joystick is not opened, it could be a guid, name, index, e.g.

I avoid opening every connected device because some controllers produces a lot of data while standing still (their sticks produces axis motion events)

Okey I resolved my issue by debugging SDL2 code.

When SDL_CONTROLLERDEVICEADDED happens, the incoming event.cdevice value is different than what is coming on SDL_CONTROLLERDEVICEREMOVED.

On SDL_CONTROLLERDEVICEREMOVED, the received value is InstanceID.

The relation is, on SDL_CONTROLLERDEVICEADDED event you should store instanceId

case SDL_CONTROLLERDEVICEADDED:
SDL_JoystickID instanceId = SDL_JoystickGetDeviceInstanceID(device);

case SDL_CONTROLLERDEVICEREMOVED:
// event.cdevice.which == instanceId stored in ADDED event

This instanceId is what you will get on SDL_CONTROLLERDEVICEREMOVED event