Re: switch statement
- Posted by DanM Mar 25, 2009
- 1389 views
I did some google searches for buggy C switch and really didn't find anything but I did find a quote on the page of PHP's switch statement (which works just like ours, and most other switch statements):
Where the switch statement wins out over an "if/elseif/else" block is it's ability to "fall though" to instructions in following cases until a break is encountered. Coding something similiar using "if/elseif/else" statements could get really messy and buggy really fast depending on the switch statement.
I tend to agree. That's why it was designed the way it is. There has been talk of implementing a select statement, but it didn't go very far for 4.0 as our plates have been full for a while. I, personally, do not see the reason for it, but others may enjoy not having to type break.
Oh, the php page does a good job of explaining switch, it's a good read for anyone interested.
Jeremy
Ok, I'm familiar from Pascal with case, but not switch, so I read both Eu 4 doc and PHP doc.
If I understand "switch" at least partly correctly, if you don't put "break" after EVERY individual case statement, EVERY case statements code will execute EVEN IF THE CASE'S CONDITION ISN'T MET? Then what are the conditions in each case statement FOR, if they're not evaluated? Have I misunderstood?
And I gotta ask, is that "fall though" expected to be the NORMAL useage of switch, and that's why break to prohibit fall through, rather than continue to allow it was chosen?
If, on the other hand, fall though would be the EXCEPTION rather than the rule, then it would seem to save a lot of typing to have used "continue" instead of "break"?
Or is it that in some programming circumstances one useage would be more prevalent, and in some other circumstances the other would be?
Dan