0

how can we use the changeable variable as a switch case label. in other words, I have a macro defined. But I need to change this value at run time depending on a condition. How can I implement this?

example is given below,

Here , case "FOO" will work?

#define CONDITION (strcmp(str, "hello") == 0)
#define FOO1 (10)
#define FOO2 (20)
#define FOO ((CONDITION) ? (FOO1) : (FOO2))


char *var="hello";

int main()
{
  int p = 20;
  switch(p) {
  case FOO:
      printf("\n case FOO");
      break;
  case 30:
      printf("\n case 30");
      break;
  default:
      printf("\n case default");
      break;
  }

    return(0);
}

2 Answers2

3

The switch condition needs to be resolved at compile-time. The case values need to be compile time constant expressions

From your question, you want to use run time condition to change the value of the case, so that is not possible.

One way to achieve run time check is to use if condition.

lolando
  • 1,721
  • 1
  • 18
  • 22
0

Your macro #define CONDITION (strcmp(str, "hello") == 0) isn't complete. It doesn't take in any argument.

The compiler will simply say str isn't defined in this scope.

Regardless, the case values are constants, so you won't be able to achieve this since your condition depends on run-time inputs.

It is important to know that most compilers implement the cases via a branch table. This is possible only because the case values are compile-time known (i.e. constants). The compiler will generate code to use your input as an index into this branch table to get to the logic for a particular case.

tl;dr - You can't use switch. Use if-elseif-else instead

Raja
  • 2,846
  • 5
  • 19
  • 28