Data type of case labels of switch statement in C++?

In C++ switch statement, the expression of each case label must be an integer constant expression.

For example, the following program fails in compilation.

filter_none

edit
close

play_arrow

link
brightness_4
code

/* Using non-const in case label */
#include<stdio.h>
int main()
{
  int i = 10;
  int c = 10;
  switch(c) 
  {
    case i: // not a "const int" expression
         printf("Value of c = %d", c);
         break;
    /*Some more cases */
                     
  }
  return 0;
}

chevron_right


Putting const before i makes the above program work.

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<stdio.h>
int main()
{
  const int i = 10;
  int c = 10;
  switch(c) 
  {
    case i:  // Works fine
         printf("Value of c = %d", c);
         break;
    /*Some more cases */
                     
  }
  return 0;
}

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<stdio.h>
int main()
{
  int n1=10,n2=11;
  
  // n1 > n2 (10 > 11) is false so using  
  // logical operator '>', n1 > n2 produces 0
  // (0 means false, 1 means true) So, case 0 
  // is executed as 10 > 11 is false. Here we 
  // have used type cast to convert boolean to int, 
  // to avoid warning.
  
  switch((int)(n1 > n2)) 
  {
    case 0:  
         printf("%d is the largest\n", n2);
         break;
    default:
         printf("%d is the largest\n", n1);
  }
  
  // n1 < n2 (10 < 11) is true so using logical 
  // operator '<', n1 < n2 produces 1 (1 means true, 
  // 0 means false) So, default is executed as we
  // don't have case 1 to be executed.
  
  switch((int)(n1 < n2))
  {
    case 0:  
         printf("%d is the largest\n", n1);
         break;
    default:
         printf("%d is the largest\n", n2);
  }
  
  return 0;
}
//This code is contributed by Santanu

chevron_right


Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Improved By : SantanuBasak, HanishGupta1

Article Tags :
Practice Tags :


7


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.