Reputation: 311
I have a set of statements that need to be executed in two different loops; the loops identified on the result of a check condition. There are multiple such sets of this type.
Set A : statement 1
statement 2
statement 3
Set B : statement 4
statement 5
statement 6
and so on..
Now they need to be executed as follows:
if(condition 1)
loop over some Loop A
execute Set A
else if(condition 2)
loop over some loop B
execute Set A
These loops can be completely different from each other.
Now, for the sake of code clarity, I don't wish to write the code as mentioned above. Another reason being I'll have to make multiple sets in order to group them together.
Is there any mechanism by which I could achieve the following:
CHECK_CONDITION_AND_LOOP_HERE
execute Set A
I've tried using macros to achieve this, using braced-group within expression but could not . I also tried using ternary operators as well as fall through a switch case to achieve this, but could not get the same result.
Is there any way in C using which I could achieve the desired behavior?
Sample code for the problem:
if(condition A)
for(i=0; i<10; i++, k*=2) {
execute Set A; //Operations performed here use variable k
}
else if(condition B)
for(j=5; j<75; j+=5, k*=arr[j]) {
execute Set A; //Operations performed here use variable k
}
Upvotes: 1
Views: 67
Reputation: 34829
The answer to Version 1 of the question:
Given that the only difference is the range of values over which the statements are executed, you can use a couple of variables to store the range end-points, e.g.
int first = 0;
int last = -1;
if (condition1) {
first = 1;
last = 10;
} else if (condition2) {
first = 3;
last = 7;
}
for ( int i = first; i <= last; i++ )
execute set A
Note that initializing last
to be less than first
prevents the body of the loop from running if neither condition is met.
The answer to Version 2 of the question:
Here's the code from the question. I've made some changes for clarity, and to make the question more concrete.
if (cond1)
for (initA;condA;updateA)
execute SetX
else if (cond2)
for (initB;condB;updateB)
execute SetX
Here's the refactored code
int is1 = cond1;
int is2 = is1 ? 0 : cond2;
if (is1)
initA;
if (is2)
initB;
while ( (is1 && condA) || (is2 && condB) )
{
execute SetX
if ( is1 )
updateA;
if ( is2 )
updateB;
}
Upvotes: 4
Reputation: 3994
A function, maybe?
void func_A() {
printf("Here0\n");
printf("Here1\n");
}
...
if(a < b) {
for(i = 1; i <= 10; i++) {
func_A()
}
}
else if(a == b) {
for(i = 3; i <= 7; i++) {
func_A()
}
}
Or if you want to only make one call/block:
if(a < b) {
min = 1; max = 10;
}
else if(a == b) {
min = 3; max = 7;
}
for(i = 3; i <= 7; i++) {
printf("Here0\n");
printf("Here1\n");
}
Upvotes: 1