Guides:C/C Crash Course/switch

From CoderGuide

Jump to: navigation, search

Back to TOC

The switch Statement

You can nest if and else statements all day, but if all you're doing trying to find out if a=1, a=2, or a=3, then you're better off using a switch statement. It takes the following form:

switch(var){
        case 1:
                do-something;
                /*If we don't have a break statement here,
                  then we'd start processing the code in the 
                  following statement.*/
                break;
        case 2:
                do-something;
                break;
        case 3: 
                do-something;
                break;
        default:
                /*var isn't 1,2, or 3. so now we stop here*/
                do-something;
                break;
}

The equivalent code using if else statements is below:

if(a==1){
        do-something;
}else if(a==2){
        do-something;
}else if(a==3){
        do-something;
}else {
        do-something;
}

As you can see, the above switch statement is a lot easier to read.

The switch statement can't compare strings. It only can compare integers and characters. If you want to compare strings, then you'll have to use nested if-else statements and the strcmp() described in the Strings section.

Personal tools