0

I have a switch in which I check a property of some sort and if the check yields a specific value, I want to check another value, so I did something like this:

switch(property_A)
{
case NA:
    if(value_0 == property_B)
        property_A = value_a;
    else if(value_1 == property_B)
        property_A = value_b;
case value_0:
...
break;
case value_1:
...
break;
}

So, I know this solves my problem, but I don't know if this is a good idea or maybe should I go about this another way

# the NA case is something like a default case but not exactly, because it does tell me something, but not enough

CIsForCookies
  • 12,097
  • 11
  • 59
  • 124

3 Answers3

4

It depends on what you want to do. If you get to the case NA, without the break keyword, the value_0 case will be executed after one of the two if branches is finished. So if that's the behaviour you want, it's OK not to use break, but I don't think that's what you wanted to do.

I suggest you simply move the if - else statement above the switch and remove the NA case. This way, you will first assign the correct data to property_A and then you can do whatever you want with it in the switch.

EDIT: As Jack Deeth points out, if you omitted the break statement on purpose, it's a good idea to add a comment that you did so.

Community
  • 1
  • 1
Honza Dejdar
  • 947
  • 7
  • 19
3

Convention is to add a comment explicitly telling future-you and any other maintainers you intended the fallthough and you haven't accidentally omitted the break;.

switch(foo) {
case 1:
  bar();
  // fallthrough
case 2:
  baz();
  break;
case 3:
  fizzbuzz();
}

If you're using C++17 or later you can use the [[fallthrough]] attribute to avoid a compiler warning:

switch(foo) {
case 1:
  bar();
  [[fallthrough]]
case 2:
  baz();
  break;
case 3:
  fizzbuzz();
}
Jack Deeth
  • 3,062
  • 3
  • 24
  • 39
2

The additional information provided in the comments to the question indicate that what's wanted is not what's written in the question:

switch(property_A)
{
  case NA:
    if(value_0 == property_B)
        property_A = value_a;
    else if(value_1 == property_B)
        property_A = value_b;
    // here, we fallthrough into the code for value_0
    // but you want to switch on the new value instead
  case value_0:
    ...
    break;
}

What you say you actually want is to set property_A if it was initially NA, then jump to the correct label. In that case, you'll need the assignment to be outside of the switch statement. You could do this with a goto at the end of the NA case, but I recommend you just deal with the NA before the switch:

if (property_A==NA)
    property_A = (value_0 == property_B) ? value_a
               : (value_1 == property_B) ? value_b
               : NA;

switch (property_A) {
  case value_0:
    ...
    break;
  case NA:
    // we get here only if none of the replacement conditions
    // matched, outside the 'case'
}
Toby Speight
  • 27,591
  • 48
  • 66
  • 103