Re: opinions on logical OR variation
From: Tim Rentsch (txr_at_alumnus.caltech.edu)
Date: 09/29/04
- Next message: Allin Cottrell: "invalid floating point value"
- Previous message: E. Robert Tisdale: "Re: #include optimization"
- In reply to: j0mbolar: "opinions on logical OR variation"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 28 Sep 2004 20:58:01 -0700
j0mbolar@engineer.com (j0mbolar) writes:
> I would like to see what the majority of people prefer
> when it comes to elegance, clarity, etc.
>
> I'll present the problem first based on
> having a product, and one product only, at a
> given time and then for each product,
> when one is chosen, we call a generic
> product function.
>
> So in the case that we have no product,
> we don't want to do anything but when we do
> we want to rely upon a single function that
> is applied to all products.
>
> #define APPLE (1<<0)
> #define ORANGE (1<<1)
> #define PEAR (1<<2)
> #define PLUMB (1<<3)
>
> int main(void)
> {
> int product = APPLE; /* start with an apple */
>
> do_something(product);
>
> return 0;
> }
>
> variations follow:
> [1]
> void do_something(int product)
> {
> int items = (APPLE | ORANGE | PEAR | PLUMB);
>
> if(product & items)
> generic_func();
>
> }
>
> [2]
> void do_something(int product)
> {
> if((product == APPLE) || (product == ORANGE)
> || (product == PEAR) || (product == PLUMB))
> generic_func();
>
> }
>
> [3]
> void do_something(int product)
> {
> switch(product) {
> case APPLE:
> case ORANGE:
> case PEAR:
> case PLUMB: generic_func();
> break;
> }
> }
>
> or perhaps you would go about it in a completely
> different way? and if so, which way?
>
>
> personally, I can't stand [2] and think it is vile.
How about [4]:
#define INTERSECTS(a,b) ( ((a)&(b)) != 0 )
void do_something(int product)
{
if( INTERSECTS( product, APPLE | ORANGE | PEAR | PLUMB ) ){
generic_func();
}
}
As other articles have pointed out, it depends on whether the
different choices are mutually exclusive or not; if they are mutually
exclusive - especially if encoded as 1, 2, 3, ... - then this approach
clearly won't work. But for the question as asked, where it looks
like the choices might be "or"ed together (which is to say, "product"
might be thought of more like a set), this variation [4] seems better
than any of [1-3]. IMO, of course.
Note that we would use a different #define if we wanted to express
different intentions, for example:
#define SUBSET_OF(a,b) ( ((a)&(b)) == (a) )
void do_something(int product)
{
if( SUBSET_OF( product, APPLE | ORANGE | PEAR | PLUMB ) ){
generic_func();
}
}
So the naming of the macro forms an important part of the clarity
of the approach exemplified by [4].
- Next message: Allin Cottrell: "invalid floating point value"
- Previous message: E. Robert Tisdale: "Re: #include optimization"
- In reply to: j0mbolar: "opinions on logical OR variation"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]