Q:

Error: duplicate case value in C

belongs to collection: C Common Errors Programs

0

Error: duplicate case value in C

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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?

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Error: Executing more than one case block in C... >>
<< Error: case label does not reduce to an integer co...