Home > Net >  I can't understand the output of this code
I can't understand the output of this code

Time:04-08

#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);
    }

}

it's oustput is:

1.one
        1.Two   1.step
2.Two   2.step  3.step

I can't understand why there are six output where it should be three I guess.

CodePudding user response:

Because without a break; statement, each case will continue into the next one.

    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);
    }

This should be properly written as:

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;
}
  • Related