1

I am confused with the following C code:

int main()
{
 const int i=2;

 switch(2)
 {
   case 1:
     printf("this is case 1");
     break;
   case i:
     printf("it should be case 2");
 }

I know after the keyword case, there should be a constant expression.

As have declared i as a constant, why is this code giving a compilation error?

kTiwari
  • 1,488
  • 1
  • 14
  • 21

4 Answers4

9

Because in C a const is not a true compile-time constant. It's just a read-only object. There's a C FAQ about this very subject.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
2

Constant variables are still not constant expressions. Constexprs (as referred to commonly) have to contain literals and compile-time constants only.

2

Reasons:

1.const cannot be used in a switch statement. You could use a #define/enum though. Refer this link.

2.There is no break for the second case.

3.There is no default case.

4.There should be a colon after case.

Community
  • 1
  • 1
Deepanjan Mazumdar
  • 1,447
  • 3
  • 13
  • 20
0

It is because you are using variable in you code.You can't use a variable in case statement. Here a is assumed as variable

The compiler is explicitly allowed to use an efficient binary tree or a jump table to evaluate case statements.

For this reason, case statements are compile time constants.

The C99 standard says this (and the C89 standard was very similar):

§6.8.4.2 The switch statement

Constraints

¶1 The controlling expression of a switch statement shall have integer type.

[...]

¶3 The expression of each case label shall be an integer constant expression and no two of the case constant expressions in the same switch statement shall have the same value after conversion. There may be at most one default label in a switch statement.

heretolearn
  • 6,387
  • 4
  • 30
  • 53