Re: compare a large number of variables
- From: mwojcik@xxxxxxxxxxx (Michael Wojcik)
- Date: 18 Aug 2005 17:11:25 GMT
In article <pan.2005.08.17.14.30.11.267556@xxxxxxxxxxx>, Netocrat <netocrat@xxxxxxxxxxx> writes:
> On Tue, 16 Aug 2005 23:55:15 -0700, Einar wrote:
>
> > Yes, your suggestions work perfectly, but I was mor looking for a nice
> > bit operator to operate on all my variables and then to compare it with
> > the value. something like (a|b|c|d...z) != value (this wont work
> > however... ).
>
> How about (off the top of my head and untested):
>
> if ( !( ((a|b|c|d...z) == value) && ((a&b&c&d...z) == value) ) )
> /* one or more of a,b,c,d...z is not equal to value */
Or the similarly silly:
if (a^value|b^value|c^value|...|z^value)
/* one or more of a,b,c,...,z is not equal to value */
(Untested, but I think that's right.) Or similarly:
if (a^b|b^c|c^d|...|y^z|z^value)
All assuming that we're working with values that aren't going to
produce trap representations, or with unsigned types.
Of course this is just a bitwise version of (in the second case):
if (a!=b || b!=c || ... || z!=value)
except that the logical version can short-circuit, so fewer
operations are performed. (Though it's conceivable that on some
systems it'd be faster to perform all the bitwise operations than
to do the comparing and branching required to implement short-
circuiting.)
> I don't think that would generally be as efficient as using multiple
> comparisons against value because in that case the first mismatch will
> prevent the rest from being evaluated.
More important, it's lousy code, and performance is rarely as
important as maintainability. And if performance *is* crucial in
this case, then it's probably time to redesign - it's unlikely that
keeping a lot of independent variables and testing them all against a
single value is actually the best way to accomplish whatever it is
that the problem requires.
That said, in some code I might find it defensible to write this as
a multiline controlling expression in an if statement (using the
logical operators, not the bitwise ones), as long as it was clear.
--
Michael Wojcik michael.wojcik@xxxxxxxxxxxxxx
Ten or ten thousand, does it much signify, Helen, how we
date fantasmal events, London or Troy? -- Basil Bunting
.
- Follow-Ups:
- Re: compare a large number of variables
- From: Netocrat
- Re: compare a large number of variables
- References:
- compare a large number of variables
- From: Einar
- Re: compare a large number of variables
- From: Eric Sosman
- Re: compare a large number of variables
- From: Einar
- Re: compare a large number of variables
- From: Netocrat
- compare a large number of variables
- Prev by Date: get current user name?
- Next by Date: Re: get current user name?
- Previous by thread: Re: compare a large number of variables
- Next by thread: Re: compare a large number of variables
- Index(es):
Relevant Pages
|