ADVERTISEMENT
ADVERTISEMENT

Error: switch quantity not an integer in C

Here, we will learn why an error: switch quantity not an integer occurs and how to fix it in C programming language?
Submitted by IncludeHelp, on September 02, 2018

The switch statement only works with integral type of values/variables, integral types like integer, character.

The error switch quantity not an integer occurs if the value/variables passed in the switch statement is not either integer or character.

In this example, consider the statement – switch(choice) – Here, choice is a float variable i.e. we have passed a float variable in switch statement, this is the cause of error switch quantity not an integer.

Example:

#include <stdio.h>

int main(void) {
	
	float  choice = 2.0f;
	
	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

prog.c: In function ‘main’:
prog.c:7:9: error: switch quantity not an integer
  switch(choice){
         ^~~~~~
prog.c:5:9: warning: variable ‘choice’ set but not used [-Wunused-but-set-variable]
  float  choice = 2.0f;
         ^~~~~~
ADVERTISEMENT

How to fix?

Use only integral variables/values with the switch statement. In this example, we changed type of choice variable from float to int.

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.