简体   繁体   English

无法理解break

[英]Trouble understanding break

Could someone please take the time and try to explain how does this code work, don't understand the break part and how the answer at the end is 0.有人可以花点时间解释一下这段代码是如何工作的,不理解中断部分以及最后的答案是 0。

int a=3, x;
switch(a==5){
   case 0: x=0;break;
   case 1: x=1;break;
   case 3: x=3;break;
   case 5: x=5;break;
   default: x=7;
}
printf("%d",x);

Without break , execution would continue from each case to the next (fallthrough) and every path would eventually end up at default and assign 7 to x .如果没有break ,执行将从每个案例继续到下一个(失败),并且每个路径最终都会以default结束并将7分配给x

Also note that you have a bug: switch(a==5) should be switch(a) .另请注意,您有一个错误: switch(a==5)应该是switch(a)

a==5 returns a true or false value (0 or 1). a==5返回真或假值(0 或 1)。 In this example, most of the cases will not be triggered.在这个例子中,大部分情况不会被触发。 Change switch(a==5) to switch(a) switch(a==5)更改为switch(a)

This means that in your example, case 0 is triggered, because a==5 results in false (0).这意味着在您的示例中,情况 0 被触发,因为a==5导致 false (0)。

Since a==5 is false, because a is 3, it returns 0. That's why case 0: is being triggered.因为a==5是假的,因为a是 3,所以它返回 0。这就是case 0:被触发的原因。

break; causes the code to stop, and without it the code would continue until default: .导致代码停止,如果没有它,代码将继续运行直到default: .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM