Why does C++ require breaks in switch statements?
This question already has an answer here:
This is for the favour of "falling throught" cases:
switch (x)
{
case 0:
case 1:
std::cout << "x is 0 or 1." << std::endl;
break;
}
In this example, the case statement is executed if x is either 0 or 1.
It is because the switch val
will be translated to a jump in assembly to specific address where case (some value):
is, then the CPU will continue executing code as normal, so fetch next address and go on, fetch next and go on, the case
blocks are in consecutive addresses in memory so the execution will fall through. break;
will tell the CPU to jump again, this time beyond the switch-case block not executing any more case
es.
The fall through might be beneficiary, and in some newer languages You must explicitly say You want it, in C and C++ the fall through is implicit.
example from my machine:
int i=1;
switch (i) {
case 1:
i=5;
break;
default:
i=6;
}
return 0;
will become
0x100000eeb: movl $0x1, -0x8(%rbp) ;int i=1;
0x100000ef2: xorl %eax, %eax
0x100000ef4: movb %al, %cl
0x100000ef6: testb %cl, %cl ;switch(i)
0x100000ef8: jne 0x100000f0f ;i is not 1 go to default:
0x100000efe: jmp 0x100000f03 ;i is 1 go to case 1:
0x100000f03: movl $0x5, -0x8(%rbp) ;case 1: i=5;
0x100000f0a: jmp 0x100000f16 ;break;
0x100000f0f: movl $0x6, -0x8(%rbp) ;default: i=6;
0x100000f16: movl $0x0, %eax ;first instruction after switch-case
if there were no jump after i=5;
then the cpu would execute the default:
as well.
Because the behaviour was inherited from C, which uses explicit break
instead. Switch fallthrough was much more useful then and that's why it was chosen as the "default" behaviour.
There was just a lot more programmer time and a lot less machine time so designing for maximum potential efficiency instead of readability made a lot more sense. And compilers had a lot less power to optimize (in many respects). You can look at things like Duff's Device for examples of how this behaviour was used.
链接地址: http://www.djcxy.com/p/84476.html上一篇: 交换机中的情况如何不会中断?