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.

/* 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;
}

Putting const before i makes the above program work.

#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;
}

Note : The above fact is only for C++. In C, both programs produce error. In C, using a integer literal does not cause error.

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




Recommended Posts:



1.5 Average Difficulty : 1.5/5.0
Based on 31 vote(s)