0

What If I have function return_num(), where I need return some value, but if I switch inserted value x, and I'm sure, that default will return value 1, if I enter anything else... Is necessary to add another return with value 1 to the end of function? Compiler does not complain.

int return_num(int x) {
   switch (x) {
       case 0: return 10;
       case 1: return 25;
       case 2: return 33;
       default: return 1;
   }
   // <--- necessary return?
}
  • 1
    Not necessary. Reference https://stackoverflow.com/questions/44567830/warning-not-all-control-paths-return-a-value-c – Paul Varghese Feb 18 '21 at 01:05
  • 2
    Personally, I would simply remove the `default` case and move that `return` to the end: `int return_num(int x) { switch (x) { case 0: return 10; case 1: return 25; case 2: return 33; } return 1; }` – Remy Lebeau Feb 18 '21 at 01:07

1 Answers1

1

Since the return type isn't void, it is indeeed necessary to not let the function execute to the end.

However, given that the switch returns in all cases, there is no need to add anything. Anything after the switch would be dead code.

eerorika
  • 232,697
  • 12
  • 197
  • 326