-3

I recently started on Codecademy, on the subject about conditions right now. I'm attempting to use both if + if else and switch + break + default. On the last step of this exercise i encountered this.

Can we use case X>y?

int max = 0;
std::string house;

switch(max){
      case gryffindor > max : max = gryffindor;
  house = "gryffindor";
     case hufflepuff > max : max = gryffindor;
  house = "hufflepuff";
     case ravenclaw > max : max = gryffindor;
  house = "revenclaw";
     case slytherin > max : max = gryffindor;
  house = "slytherin";
        }
xryl669
  • 3,376
  • 24
  • 47

1 Answers1

-1

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):

  1. Let's say you have a value that can go from 0 to 9.
  2. Create a switch on this value and 10 cases from 0 to 9.
  3. The compiler will create a table containing 10 entries (which are the address of the code in memory for each case)
  4. 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.

xryl669
  • 3,376
  • 24
  • 47