Home > Net >  How to branch conditionally in C to a label given by an arithmetic operation or lookup table
How to branch conditionally in C to a label given by an arithmetic operation or lookup table

Time:12-24

Instead of writing an if or a switchstatement, like this:

if (a == 1)
    <some code here 1>
else if (a == 2)
    <some code here 2>
else if (a == 3)
    <some code here 3>

I want to run somthing like this:

l[1] = here1;
l[2] = here2;
l[3] = here3;

goto l[a];

here1:
    <some code here 1>
here2:
    <some code here 2>
here3:
    <some code here 3>

Is it possible to do this in C?

CodePudding user response:

No it isn't but there is a GCC extension for that. https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html#Labels-as-Values.

So your code would be:

void *l[3] = {&&here1, &&here2, &&here2};

goto *l[a];

here1:
    <some code here 1>
here2:
    <some code here 2>
here3:
    <some code here 3>
  • Related