开发者

How Does Case 5 executed in this Switch statement?

开发者 https://www.devze.com 2023-04-08 11:22 出处:网络
I have a following code(which is taken from a C book): #include<stdio.h> int main( ) { int k=4,j=0;

I have a following code(which is taken from a C book):

#include<stdio.h>

int main( )
{
  int k=4,j=0;

  switch(k)
  {
  case 3:
    j=300;

  case 4:
    j=400;

  cas开发者_StackOverflow社区e 5:
    j=500;
  }

  printf("%d",j);
}

When i run the above code, I get output as 500, but I expected it to be 400, can anyone why it is been printed 500 rather than 400?

(I am novice in C and I couldn't figure out what is the error in it!)


You need to break; at the end of a case block.

#include <stdio.h>
int main()
{
    int k = 4, j = 0;
    switch(k)
    {
        case 3:
            j = 300;
            break;
        case 4:
            j = 400;
            break;
        case 5:
            j=500;
            break;
    }
    printf("%d\n", j);
}


You need to break out of your cases otherwise it will run trough other cases:

int main( )
{
    int k=4,j=0;
    switch(k)
    {
    case 3:
        j=300;
        break;
    case 4:
        j=400;
        break;
    case 5:
        j=500;
        break;
    }
    printf("%d",j);
}

So in your case it did execute j=400 and then went to case 5: and execute j=500


There's no break statement after case 4, so execution "falls through" to case 5.

0

精彩评论

暂无评论...
验证码 换一张
取 消