Reputation: 1551
I was trying to count how many out of my four variables were greater than 0, so I wrote these if statements to achieve my purpose. All numbers will be positive or 0:
if(a1>0){counter++;}
if(a2>0){counter++;}
if(a3>0){counter++;}
if(a4>0){counter++;}
printf("%d", counter);
It's quite obvious that I would run into some trouble if the number of variables were to increase. Is there a more efficient way of writing this?
Thanks for taking the time to help me.
Upvotes: 1
Views: 1094
Reputation: 11162
If you're looking for a single statement,
counter+= (a1>0) + (a2>0) + (a3>0) + (a4>0);
Should do. If you decide to pack your data into an array,
#define SIZE(x) (sizeof(x)/sizeof*(x))
int x, a[4];
for(x=0; x<SIZE(a); x++)
counter += (a[x]>0);
Is still reasonably compact.
Upvotes: 6
Reputation: 6740
What if you just used an array? such as this:
int a[4];
int counter;
int i; // iterator
for(i=0;i<4;i++){
if(a[i]>0){
counter++;
}
}
printf("%d", counter);
that would be faster, shorter code, but your way is efficient as possible if you must have separate variables.
Upvotes: 3
Reputation: 821
If all variables are of the same type, you can store pointers to them in a array and use a loop to check and increment the counter.
Upvotes: 0
Reputation: 150108
Fundamentally you have to tell the compiler which memory address to check, and where to put the result.
If you have lots of local variables, you probably want to consider an array or similar data structure to hold them rather than tons of separately declared variables. In that case, you could define an array to hold the counter results too, and use a loop construct.
If you do not have tons of local variables, I suspect your current approach is about as good as it gets (you could get fancy by placing a pointer to each variable in an array and then using a loop, but the array initialization would be at least as cumbersome as the current if
statements).
I would not change your program logic to use arrays if named, individual variables are a more natural fit.
Upvotes: 5
Reputation: 6359
Use an array rather than separate variables. Then just loop through the array.
Upvotes: 0