辽宁葫芦岛在哪里:开关语句问题,请帮忙解答一下,谢谢!!

来源:百度文库 编辑:查人人中国名人网 时间:2024/04/28 19:27:47
(1)
switch (++i) {
case 1: case 2: case 3:
cout<<"Yes"<<endl;
break;
case 5: case 6:
cout<<"No"<<endl;
case 10: case 11:
cout<<"Maybe"<<endl;
break;
default:
cout<<"Sometimes"<<endl;
}
if i is 6,what is the output of the above code?
i=6,表达式++i的值是7,应该输出Sometimes, 答案为什么是No?

我运行了一遍
运行结果:
Sometimes
Press any key to continue

答案不一定是对的
既然不明白为什么不动手运行一下呢

因为 ++i 是你运行完switch语句后才执行 i = i + 1 的。
所以你的程序在进switch做判断时是6。
^_^

答案是Sometimes,XPSP2+VC6环境下验证。永远不要相信书本的答案。