Why did I place a break statement at the end of each case label? Each
case label is tested in turn against the expression's value. Each
nonmatching case label is skipped in turn. When a case label matches the
value, execution begins with the statement following the case label. The
"gotcha" is that execution continues through each subsequent case
statement until the end of the switch statement. If num_tries equals 2, for
example, and if there was no break statement, the output would look like
this:
參考答案:我为什么要在每个 case 标号的结尾要放一个 break 语句呢?所有case 标号都是依次来检查表达式的值的。每个不匹配的 case 标号都依次被跳过。当有个 case 标号与其值匹配时,执行就从该 case 标号后面的语句开始。它的“缺陷”就是其执行会继续穿过每个后续的 case 语句直到此 switch 语句的结尾。比如说,如果 num_tries 等于 2,而且若其中没有 break 语句,它的输出看起来就是这样: