I want to case switch a varying number of items (a vector), but this method requires constants. I am using SDL2 to read all the inputs, and the method I am using requires a case switch. I need to get all the inputs pressed and add those to a string or vector of some sort.
while (SDL_PollEvent(&e) != 0){
switch (e.type){
for (int i = 0; i < currentbinds.size(); i++){
case currentbinds[i]:
keyspressed += currentbinds[i];
}
case SDL_QUIT:
iskillready = true;
break;
}
}
}
currentbinds is a vector containing all possible keybinds that I might use. keyspressed is a string that returns all the keybinds that are pressed. I am using a case switch to go through all the keybinds, checking if that keybind is pressed, and if so, adding them to the keyspressed string.
Is there any other way to do this without constants?
The primary purpose of using a switch statement in C++ (and many other programming languages) is to improve the readability and maintainability of code when you have a limited set of constant values to compare against. It's especially useful when you have a long list of constant values to compare because it makes the code more structured and easier to follow.
When you don't have constant values to use as labels, using a switch statement may not be appropriate or readable, and using other control structures like if statements or loops is often a more suitable choice.
Simply, in this case use if instead of switch like:
while (SDL_PollEvent(&e) != 0) {
if (e.type == SDL_QUIT) {
iskillready = true;
continue;
}
for (int i = 0; i < currentbinds.size(); i++) {
if (e.type == currentbinds[i]) {
keyspressed += currentbinds[i];
}
}
}
Edited to comply with the original code logic.