-
switch statement
Hello.
I was wondering if it is "healthy" to define return statements in each switch statement, I mean:
Code:
int function (...)
{
int data;
...
switch (option)
{
case 'A': return (data+1)
break;
...
case 'Z': return (data+26);
break;
}
}
It seems there is no need to use break...?
-
What you could do is have an extra variable to be your return value. In the switch, you can set the return value there, and then return after the switch.
-
Well MacGyver's idea would work fine, but really you don't even need an extra variable, just do something like this:
Code:
int function (...)
{
int data;
...
switch (option)
{
case 'A': data += 1;
break;
...
case 'Z': data += 26;
break;
}
return(data);
}
Personally i'd consider this better style than what you are doing now, and it's not harder to read or understand either...
-
In this particular case, going by the pattern presented, my inclination would be to get rid of the switch entirely.
Code:
return data + (option - 'A' + 1);
(Of course noting possible character set issues.)
As far as switch cases, I have no issue using a return (and not needing a break after the return). The "problem" that the single point of return argument is supposed to solve tends to confuse me more than this returning "early" that I find simpler. YMMV.
-
Thanks for your answer.
I would like to know if it's just matter of style or it is wrong to do it this way (my way)?
-