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?
#include<stdio.h>
int main() {
        int const x = 20;
        int y = 20;
        switch (y) {
        case x:
                printf("value of x: %d\n", x);
                break;
        }
}

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.
#include<stdio.h>

int main() {
        int j = 4;
        switch (j) {
        case 1:
        case 2:
                printf("world");
        default:
                printf("hello\n");
        }

        return 0;
}
// output 
// hello
  • 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?
#include<stdio.h>

int main() {
	char j = '3';
	switch (j) {
	case 1:
	case 2:
	case 3:
		printf("case 3");
	default:
		printf("hello\n");
	}

	return 0;
}

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.
#include<stdio.h>

int main() {
	int j = 3;
	switch (j) {
	case 1:
	case 2:
	case 3:
		printf("case 3\n");
	case 4:
			printf("case 4\n");
	default:
		printf("hello\n");
	}

	return 0;
}

output:

case 3
case 4
hello
  • To execute only the matched case label use break statement.
#include<stdio.h>

int main() {
	int j = 3;
	switch (j) {
	case 1:
	case 2:
	case 3:
		printf("case 3\n");
		break;
	case 4:
			printf("case 4\n");
	default:
		printf("hello\n");
	}

	return 0;
}

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.
#include<stdio.h>

int main() {
	int j = 3;
	switch (j) {
	case 1:
	case 2:
	case 2:
	default:
		printf("hello\n");
	}

	return 0;
}
  • expressions are allowed in switch statement provided expression involves only int and char.
#include<stdio.h>

int main() {
	int j = 1;
	int i = 14;
	switch ((i+j)/5) {
	case 1:
	case 2:
		printf("case 2\n");
	case 3:
		printf("case 3\n");
		break;
	default:
		printf("hello\n");
	}

	return 0;
}

 

Ref:

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



Related Contents to follow