Wednesday, 16 March 2016

What should be 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 */
                    
  }
  getchar();
  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 */
                    
  }
  getchar();
  return 0;
}

0 comments:

Post a Comment