Roh
Roh

Reputation:

Switch case in C

Can someone help with the below

#include <stdio.h>

main ()
{
    char receive_buff [] ={0x01,0x00,0x01,0x01,0x00,0x00};

    switch( receive_buff[0] ) 
    {
        case 0x00:
            {printf("\nswitch 00\n");}
        case 0x01:
            {printf("\nswitch 01\n");}
        case 0x02:
            {printf("\nswitch 02\n");}
        default :
            {printf("\nswitch default\n");}
    }
}

the result is

 ./a.out 

switch 01
Ro
switch 02

switch default

I don't know what going on here.

Upvotes: 0

Views: 5745

Answers (2)

Winston Ewert
Winston Ewert

Reputation: 45049

switch( receive_buff[0] ) 
{
    case 0x00:
        {printf("\nswitch 00\n");}
    case 0x01:
        {printf("\nswitch 01\n");}
    case 0x02:
        {printf("\nswitch 02\n");}

    default :
        {printf("\nswitch defualt\n");}
}

Should be

switch( receive_buff[0] ) 
{
    case 0x00:
        {printf("\nswitch 00\n");}
        break;
    case 0x01:
        {printf("\nswitch 01\n");}
        break;
    case 0x02:
        {printf("\nswitch 02\n");}
        break;
    default :
        {printf("\nswitch defualt\n");}
        break;
}

Upvotes: 6

Daniel Pittman
Daniel Pittman

Reputation: 17202

You need a break statement after each set of actions, or the C switch will fall through. See http://en.wikipedia.org/wiki/Switch_statement#C.2C_C.2B.2B.2C_D.2C_Java.2C_PHP.2C_ActionScript.2C_JavaScript

Upvotes: 5

Related Questions