0

Suppose I have a variable, int x, deciding in a switch/case, and I want two possible actions: one for x=1, x=2, x=5 and another for x=3, x=4. Is the following code acceptable in terms of codiquette?

switch (x)
{
case 1:
case 2:
default:
    // do something
case 3:
case 4:
    // do something else
}

I realize it also works for x>5, but that's not a problem in my case, and it seems to work, gcc 6.1.1, archlinux 64. The reason is that do something involves calling a not-so-small function and I'd like to avoid writing it twice (code bloating?), even if it's just a matter of copy-paste.

a concerned citizen
  • 787
  • 2
  • 9
  • 25
  • This is for C but it should be the same rules: http://stackoverflow.com/questions/3110088/switch-statement-must-default-be-the-last-case – NathanOliver Aug 25 '16 at 15:15
  • @NathanOliver Thank you, that answers my question. If you make this an answer, I'll mark it down. Actually, now that I think of it, I think this can be marked as duplicate? – a concerned citizen Aug 25 '16 at 15:18
  • I closed it as a dupe since you are okay with it. I normally do not do that because of the different language tags, – NathanOliver Aug 25 '16 at 15:19
  • And don't forget the `break;` to avoid the fall-through. – Jarod42 Aug 25 '16 at 15:20
  • just to the "orthodoxy" part: It can be confusing and people may oversee that in maintanence. You should maybe annotate those parts with comments when you do it in your code so it does not gets easily overseen. And in case you stumble across c++17 in future check out the `[[fallthrough]]` attribute – Hayt Aug 25 '16 at 15:24
  • @Jarod42 I don't, just didn't see fit throwing a `break` after a comment :-) #Hayt That was my main concern. For my particular case, I commented out the `case 5:` part, quote: `It seems if I set this to default and move it after 1,2,3, it works. Not sure how orthodox it is, though.` As for the `[[fallthrough]]` part, I may wait for it because I'd like tho code to be able to be compiled on some older machines, too. – a concerned citizen Aug 25 '16 at 15:31

0 Answers0