Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why case: always requires constant expression while if() doesn't?

May be possible duplicate but couldn't have found the same.

Suppose I have following C code :

int a;
printf("Enter number :");
scanf("%d",&a);  // suppose entered only an integer
                // ignoring return value of scanf()

I got a case to check whether a is zero or non-zero.

if(a)
  printf("%d is non-zero",a);
else
  printf("%d is zero",a);

Everything is fine using if-else and I also know the other variations of if-else to achieve this . But problem comes with the switch-case as it says that we can implement everything in switch-case which we can do in if-else. But the following code fails.

switch(a)
{
 case a:
       printf("%d is non-zero",a);
       break;
 default:
       printf("%d is zero",a);
       break;
}

Also I know to reverse the case in the above code like this below will work and I will have my answer.

switch(a)
{
case 0:
    printf("%d is zero",a);
    break;
default :
    printf("%d is non-zero",a);
    break;
}

But the question is, Why ? Why if(a) is valid while case a: is not ? Is switch-case a compile time operation and if() run-time ?

like image 823
Omkant Avatar asked Dec 21 '12 18:12

Omkant


People also ask

What is constant expression?

A constant expression is an expression that can be evaluated at compile time. Constants of integral or enumerated type are required in several different situations, such as array bounds, enumerator values, and case labels. Null pointer constants are a special case of integral constants.

What is the meaning of constant expression required error in C?

A constant must be initialized. This error has the following causes and solutions: You tried to initialize a constant with a variable, an instance of a user-defined type, an object, or the return value of a function call.

What is constant expression in Java?

A constant expression is an expression that contains only constants. A constant expression can be evaluated during compilation rather than at run time, and can be used in any place that a constant can occur.


1 Answers

The reason is that switch cases can be implemented as jump tables (typically using unconditional branch instructions). So they have to be resolved at compile time.

This makes them faster than ifs so it is better to use them when possible.

like image 133
imreal Avatar answered Oct 05 '22 19:10

imreal