首先明确一点default不同位置输出是不同的:
例子;
#include <iostream> using namespace std; int main() { int a=1,b=2,c=3,d=4,y=10; switch(y){ case 1:a++;break; default:d=1; case 2:b++;break;//b是可以跑进去的 case 4:c++;break; } cout << a<<b<<c<<d<< endl; return 0; }
结果:
1331
例子:
#include <iostream> using namespace std; int main() { int a=1,b=2,c=3,d=4,y=10; switch(y){ case 1:a++;break; case 2:b++;break; default:d=1; case 4:c++;break; //c++是跑进去了 } cout << a<<b<<c<<d<< endl; return 0; }
结果:
1241
解释:这是在程序中debug的,原理:程序一步一步的跑,遇到default包进去,接下来语句包进去,遇break跳出switch,就是结果,网上有很多不对,注意。下面是debug截图。再来一个例子:
#include <iostream> using namespace std; int main() { int a=1,b=2,c=3,d=4,y=10; switch(y){ case 1:a++;break; default:d=1;
case 2:b++; case 4:c++;break; } cout << a<<b<<c<<d<< endl; return 0; }
结果:
1341