package mainimport "fmt"func main() { var i int = 10 switch true { case i < 20: fmt.Printf("%v is less than 20\n", i) i = 100 fallthrough case i < 19: fmt.Printf("%v is less than 19\n", i) fallthrough case i < 18: fmt.Printf("%v is less than 18\n", i) fallthrough case i > 50: fmt.Printf("%v is greater than 50\n", i) fallthrough case i < 19: fmt.Printf("%v is less than 19\n", i) fallthrough case i == 100: fmt.Printf("%v is equal to 100\n", i) fallthrough case i < 17: fmt.Printf("%v is less than 17\n", i) }}输出:10 is less than 20100 is less than 19100 is less than 18100 is greater than 50100 is less than 19100 is equal to 100100 is less than 17这是预期的行为吗?
2 回答

临摹微笑
TA贡献1982条经验 获得超2个赞
该fallthrough
语句将控制权转移到下一个case
块的第一条语句。
该fallthrough
语句并不意味着继续计算 next 的表达式case
,而是无条件地开始执行下一个case
块。
引用fallthrough
声明文档:
“fallthrough”语句将控制转移到表达式“switch”语句中下一个 case 子句的第一个语句。
引用switch
声明文档:
在 case 或 default 子句中,最后一个非空语句可能是(可能标记为)“fallthrough”语句,以指示控制应该从该子句的末尾流向下一个子句的第一个语句。否则控制流到“switch”语句的末尾。

慕森王
TA贡献1777条经验 获得超3个赞
是的,正如 icza 所指出的那样。
如果您不想在第一个 case 块之后落入每个 case 块,请删除fallthrough
行(就像您不会break
在每个 C/C++ case 块的末尾放置一行。
而且,正如您在评论中所期望的那样,评估在switch()
达到时完成,之后无论您是否更改i
值,都不会在每个案例块上再次评估。
- 2 回答
- 0 关注
- 155 浏览
添加回答
举报
0/150
提交
取消