Will the default of a switch statement get evaluated if there's a matching case before it?
ex:
switch ($x) {
case ($x > 5): print "foo";
case ($x%2 == 0): print "bar";
default: print "nope";
}
so for x = 50, you'd see foo
and bar
, or foo
and bar
and nope
?
Yes, if there is no "break", then all actions following the first
case
matched will be executed. The control flow will "falls through" all subsequentcase
, and execute all of the actions under each subsequentcase
, until abreak;
statement is encountered, or until the end of theswitch
statement is reached.In your example, if $x has a value of 50, you would actually see
"nope"
.Note that
switch
is actually performing a simple equality test, between the expression following theswitch
keyword, and each expression following thecase
keyword.Your example is unusual, in that it will only display
"foo"
when $x has a value of 0. (Actually, when $x has a value of 0, what you would see would be "foo bar nope".)The expression following the
case
keyword is evaluated, which in your case, example return a 0 (if the conditional test is false) or a 1 (if the conditional test is true). And it's that value (0 or 1) thatswitch
will compare to$x
.In most
case
s it shouldn't, because you would often havebreak
s in there. However in your case it would also go to thedefault
.Also please try to prevent to do those single line stuff (for readability):
Will print
foobarnope
. So to answer your question: yep :-)It would have been easier to try it yourself. but anyway, if you don't use break in a case, all the the cases following it will be executed (including the default)
That's not how switches work.
According to the manual:
An evaluation like
simply equates to
or
depending on the value of
$x
because($x > 5)
is an EVALUATION, not a VALUE. Switches compare the value of the parameter to see if it equates to any of thecase
s.The comparison in the above code is equivalent to
which (when
$x == 50
) is equivalent towhich is equivalent to
IF, however, you used your switch statement as it is intended to be used (to compare the parameter to concrete values):
and
$x == 50
, your output would bedue to the fact that you have no
break
in your cases.Had you added the
break
keyword to the end of each case, you would only execute the code for that specific case.Output: