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.
source to share
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;
source to share
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;
source to share