ADVERTISEMENT
ADVERTISEMENT

Error: Executing more than one case block in C

Here, we will learn why more than multiple case blocks execute in C program and how to fix it?
Submitted by IncludeHelp, on September 02, 2018

Executing more than one case block in C – is not a syntax error, it's a logical error and it occurs when you miss to place break statement in the case block.

In C programming language, it's a feature of the switch case statement, that you can place a single case block for multiple case values, in that case – there is no need to place break in the case block.

But, if you want to execute one block with one case value, you have to place break statement with each case block.

Example:

#include <stdio.h>

int main(void) {
	
	int choice = 2;
	switch(choice){
	    case 1:
	        printf("Case 1\n");
	    case 2:
	        printf("Case 2\n");
	    case 3:
	        printf("Case 3\n");
	    case 4:
	        printf("Case 4\n");
	    default:
	        printf("Case default\n");
	}
	
	return 0;
}

Output

Case 2
Case 3
Case 4
Case default
ADVERTISEMENT

How to fix?

Use break with each case block.

Correct code:

#include <stdio.h>

int main(void) {
	
	int choice = 2;
	switch(choice){
	    case 1:
	        printf("Case 1\n");
	        break;
	    case 2:
	        printf("Case 2\n");
	        break;	    
	    case 3:
	        printf("Case 3\n");
	        break;	    
	    case 4:
	        printf("Case 4\n");
	        break;	    
	    default:
	        printf("Case default\n");
	}
	
	return 0;
}

Output

Case 2

C Common Errors Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.