Is there a way to combine multiple different conditionals with a common expression?

Is there a way to combine multiple different conditionals with a common expression?

For example:

int a;
...
if (a == 1){
    foo;
    ...
    return K1;
}
else if (a == 2){
    foo;
    ...
    return K2;
}
...
else if (a == i){
    foo;
    ...
    return Ki;
}

      

Is there a sane way to deduce foo

, but only do it under these conditions? (Similar to factorization in algebra: 2x + 6 = 2 (x + 3)).

It feels repetitive, so I suppose there must be a way to make it shorter.

+3


source to share


5 answers


Will your scenario be something like this?



int a;
int k; // let assume int
...
k = a == 1? K1:
    a == 2? K2:
    ...
    a == i? Ki:
    K0; // a special value
if (k != K0)
    foo;
return k;

      

+3


source


Assuming the return value is of type int

(change it accordingly). You can use the following:



int a;
int retVal;
int execFoo;

execFoo = 0;
...
if (a == 1){
    execFoo = 1;
    ...
    retVal = K1;
}
else if (a == 2){
    execFoo = 1;
    ...
    retVal = K2;
}
...
else if (a == i){
    execFoo = 1;
    ...
    retVal = Ki;
}

if(execFoo == 1)
    foo;
return retVal;

      

+1


source


Expanding on WeatherVane's comment about array - values ​​can always be stored in an array, even if they haven't made it to the block in question - just add them to the new one:

T array[] = { [1] = K1, K2, K3, ..., Ki };
foo();
return a <= i && a > 0 ? array[a] : K0;

      

+1


source


I think it is better to use a helper function to get the k

corresponding a

one and then use the value k

to call foo

or not.

// Function to get K given a.
int getK(int a)
{
   switch (a)
   {
      case 1:
         return K1;

      case 2:
         return K2;

      default:
         return K_Unknown;
   }
}

      

Using the function:

int a;
int k = getK(a);
if ( k != K_Unknown )
   foo;

      

+1


source


You can #define the macro IF(cond) if ((cond) && (<foo>, 1))

and #undef it after all the blocks:

#define IF...
IF (a == 1) { ... }
else IF (a == 2) { ... }
#undef IF

      

(assuming that <foo>

is the only expression)

+1


source







All Articles