我无法理解这段代码的输出
I can't understand the output of this code
#include<stdio.h>
int main()
{
int a=1,i;
for(i=0;i<3;i++)
switch((++a)-1)
{
case 0:printf("\nzero");
case 1:printf("%d.one",i+1);
case 2:if(i%2==0)
printf("\n\t%d.Two",i+1);
else
printf("\n%d.Two",i+1);
default:printf("\t%d.step",i+1);
}
}
它的输出是:
1.one
1.Two 1.step
2.Two 2.step 3.step
我不明白为什么有六个输出我猜应该是三个。
因为没有break;
声明,每个案例都会继续到下一个。
switch((++a)-1)
{
case 0:printf("\nzero"); // Without a break;, the next line gets executed as well!
case 1:printf("%d.one",i+1); // Execution continues here, printing "%d.one", even though we are in case 0
case 2:if(i%2==0)
{
printf("\n\t%d.Two",i+1);
}
else
{
printf("\n%d.Two",i+1);
} // The default will get run as well, for lack of a "break;"
default:printf("\t%d.step",i+1);
}
这应该正确地写成:
switch((++a)-1)
{
case 0:
printf("\nzero");
break;
case 1:
printf("%d.one",i+1);
break;
case 2:
if(i%2==0)
{
printf("\n\t%d.Two",i+1);
}
else
{
printf("\n%d.Two",i+1);
}
break;
default:
printf("\t%d.step",i+1);
break;
}
#include<stdio.h>
int main()
{
int a=1,i;
for(i=0;i<3;i++)
switch((++a)-1)
{
case 0:printf("\nzero");
case 1:printf("%d.one",i+1);
case 2:if(i%2==0)
printf("\n\t%d.Two",i+1);
else
printf("\n%d.Two",i+1);
default:printf("\t%d.step",i+1);
}
}
它的输出是:
1.one
1.Two 1.step
2.Two 2.step 3.step
我不明白为什么有六个输出我猜应该是三个。
因为没有break;
声明,每个案例都会继续到下一个。
switch((++a)-1)
{
case 0:printf("\nzero"); // Without a break;, the next line gets executed as well!
case 1:printf("%d.one",i+1); // Execution continues here, printing "%d.one", even though we are in case 0
case 2:if(i%2==0)
{
printf("\n\t%d.Two",i+1);
}
else
{
printf("\n%d.Two",i+1);
} // The default will get run as well, for lack of a "break;"
default:printf("\t%d.step",i+1);
}
这应该正确地写成:
switch((++a)-1)
{
case 0:
printf("\nzero");
break;
case 1:
printf("%d.one",i+1);
break;
case 2:
if(i%2==0)
{
printf("\n\t%d.Two",i+1);
}
else
{
printf("\n%d.Two",i+1);
}
break;
default:
printf("\t%d.step",i+1);
break;
}