In this tutorial we are going to learn some interesting facts of switch statement in c programming. switch case is used to jump at a section of the code in c program. The switch statement transfers control to a statement within its body. I think we already have basic working knowledge of switch case in c. Let us discuss some interesting facts.

  • Let us try to compile below c program. will this code compile?

The above code will not compile. It will give compile time error ”¬†error: case label does not reduce to an integer constant”.¬† So a case label requires constant expression.

  • when there is no match case label and if there is default label then control reaches to default case label.

  • The constant-expression for a case must be the same data type as the variable in the switch. Let us see below code , will it compile?

The above code will compile successfully. It will give output “hello” because there is no match case found so default case would be executed.

  • When the variable being switched on is equal to a case, the statements following that case will execute and all other statement following the matched case will be executed.

output:

  • To execute only the matched case label use break statement.

The above program switch at case 3, executes printf statement and comes out of switch body. so it will output only “case 3”.

  • Two case label cannot have same value. so the below program will error out.

  • expressions are allowed in switch statement provided expression involves only int and char.

 

Ref:

https://msdn.microsoft.com/en-us/library/66k51h7a.aspx




Related Contents to follow