switch(X)
is a "jump to value" shortcut. It's in the language because a very simple and effective optimization exists to implement this.
For this optimization to work, the possible value must be static and known at compilation time. So you can not have a dynamic/runtime Y in your case Y:
destination.
The optimization is doing this way (simplified):
- Let's say you have a value that can go from 0 to 9.
- Create a switch on this value and 10 cases from 0 to 9.
- The compiler will create a table containing 10 entries (which are the address of the code in memory for each case)
- When testing the value, the compiler only have to jump to the address contained in the table at position value, unlike following a long if/else test chain.
This will not work in your case, you'll have to create a chain of if/else
like this:
enum House { gryffindor, hufflepuff, ravenclaw, slytherin };
std::string getHouse(House house, int & max) {
max = 0;
if (house == gryffindor) max = gryffindor;
else if (house == hufflepuff) max = hufflepuff;
else if (house == ravenclaw) max = ravenclaw;
else max = slytherin;
switch(max){
case gryffindor: return "gryffindor";
case hufflepuff: return "hufflepuff";
case ravenclaw : return "revenclaw";
case slytherin : return "slytherin";
default: return "none";
}
}
If you are not returning after a case, you must use break;
to exits the switch
block.