×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

Error: duplicate case value in C

Here, we will learn why an error: duplicate case value is occurred in C programming language and how to fix it?
By IncludeHelp Last updated : March 10, 2024

Error: duplicate case value

The error: duplicate case value occurs in C programming, if there are two duplicate case values in the switch statement.

Example

Consider the below program – In this program, there are two case values, which are same. "Case 2" exists two times in the program.

#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;	    
	    case 2:
	        printf("Case 5\n");
	        break;	    
	    default:
	        printf("Case default\n");
	}
	
	return 0;
}

Output

prog.c: In function ‘main’:
prog.c:19:6: error: duplicate case value
      case 2:
      ^~~~
prog.c:10:6: error: previously used here
      case 2:
      ^~~~

How to fix - Error: duplicate case value

To fix the error: duplicate case value in C language, either remove the duplicate case and its block or change the duplicate case value.

Correct Code

Here, I am removing the duplicate case "Case 2" which is exist second time in the program.

#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 »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.