I have a code snippet where a do while statement is inside switch condition of case0, by default the case value is case1 but it seems executing case0. The output of the program print is 6. How is this possible, can someone explain the flow of code here. Thanks in advance for your answers.
int main()
{
int a = 1, t =0,n=2;
switch(a)
{
case 0:
do
{
t++;
case 4:t++;
case 3:t++;
case 2:t++;
case 1:t++;
}while(--n>0);
printf("%d",t);
}
return(0);
}
Switch cases are similar to labels for
goto
.You start at
case 1
, which is inside the loop – effectively using that as your starting point – and then execute the loop normally while "falling through" the cases as you go.Here is the equivalent using
goto
:(The actual generated code might use a jump table rather than a series of conditionals, but the behaviour is the same.)