I’m working on a c++ project that reads MIDI-data from an external USB-device. The program is supposed to call certain functions depending on which fader/knob/button on the USB-device is shiftet/rotated/pressed (such as vol +- or mute/unmute channel).
The only way I came up with finding out which fader/knob/button was changed was using a pretty big switch statement that basically checks every incoming midi event.
looks sort of like this :
switch(MidiMessage.get2ndByte()){
case 1 : cout << "Fader 1 Value : " << MidiMessage.get3rdByte() << endl;
case 2 : cout << "Fader 2 Value : " << MidiMessage.get3rdByte() << endl;
case 10 : cout << "Button 1 Value : << "MidiMessage.get3rdByte() << endl;
...
...
...
}
Isn’t there a more efficient/smart way to do this?
Since your switching is done on a byte (and thus just has 256 different values; I’m pretty sure MIDI files are based on 8-bit bytes), the best option is probably to use a simple array of function pointers:
This array just uses 1KB (32 bit platforms) or 2KB (64 bit platforms), gives guaranteed constant time lookup, has no hidden overhead, and possibly your compiler implements your big switch statement internally as lookup table anyway (so the only overhead you get is an extra function call).
Note that if there are invalid byte values, the array entry should point to an explicit error function (instead of a simple 0), so your program can handle the error gracefully.