题目
以下程序的输出结果是( )。#include<stdio.h>void main()(int x=1,y=0,a=0,b=0;switch(x){case 1:switch(y){case 0:a++;break;case 1:b++;break;)case 2:a++;b++;break;}printf("a=%d,b=%d",a,b);}
以下程序的输出结果是( )。
#include<stdio.h>
void main()
{
int x=1,y=0,a=0,b=0;
switch(x)
{
case 1:switch(y)
{
case 0:a++;break;
case 1:b++;break;
}
case 2:a++;b++;break;
}
printf("a=%d,b=%d",a,b);
}
题目解答
答案
a=2,b=1
解析
本题考查嵌套switch语句的执行流程,关键在于理解switch语句中没有break时的“ fall through”现象。
- 外层switch的条件是
x=1,会执行case 1中的代码块。 - 内层switch的条件是
y=0,执行case 0中的a++,随后break跳出内层switch。 - 由于外层
case 1末尾没有break,程序会继续执行后续的case 2代码块,导致a和b再次被修改。
外层switch(x=1)的执行过程
- 进入case 1:
- 执行内层switch(y=0):
- 进入case 0,执行
a++→a=1。 break跳出内层switch。
- 进入case 0,执行
- 外层
case 1末尾无break,程序继续执行后续代码。
- 执行内层switch(y=0):
- 进入case 2:
- 执行
a++→a=2,b++→b=1。 break跳出外层switch。
- 执行
最终结果
a=2,b=1。