Data type of case labels of switch statement in C++?
Last Updated :
12 Aug, 2021
In C++ switch statement, the expression of each case label must be an integer constant expression.
For example, the following program fails in compilation.
CPP
#include<stdio.h>
int main()
{
int i = 10;
int c = 10;
switch (c)
{
case i:
printf ( "Value of c = %d" , c);
break ;
}
return 0;
}
|
Putting const before i makes the above program work.
CPP
#include<stdio.h>
int main()
{
const int i = 10;
int c = 10;
switch (c)
{
case i:
printf ( "Value of c = %d" , c);
break ;
}
return 0;
}
|
Note : The above fact is only for C++. In C, both programs produce an error. In C, using an integer literal does not cause an error.
Program to find the largest number between two numbers using switch case:
C
#include<stdio.h>
int main()
{
int n1=10,n2=11;
switch (( int )(n1 > n2))
{
case 0:
printf ( "%d is the largest\n" , n2);
break ;
default :
printf ( "%d is the largest\n" , n1);
}
switch (( int )(n1 < n2))
{
case 0:
printf ( "%d is the largest\n" , n1);
break ;
default :
printf ( "%d is the largest\n" , n2);
}
return 0;
}
|
Share your thoughts in the comments
Please Login to comment...