how to simplify many OR in if statement?

S

Simon Cooke

I have many OR in the if statement, any method to simplify?

if (val == 5 | val == 9 | val == 34 | val == 111 | val == 131 | .......)
// ....

thank you

Could you give a more specific example of what you're trying to do with
your test?

If you're trying to sieve out these different values, it's a different case
than if you're trying to run special case code for some other reason.

For example, depending on what you're doing, it might make more sense to do
this:

bool hit = false;
if (val == 5) {
do something
hit = true;
}
else if (val == 32 || val = 64) {
do something else
hit = true;
}

if (hit) { do something if any of them were matched }
 
B

Bob Summers

On 23 Dec 2003 20:13:53 EST, (e-mail address removed) (Bob
Summers) wrote:

[snip]
Even if you ignore the possibility that boolean_array[val] has a
non-false value other than true, the use of "x == true" bugs me
because when you use "==" to compare booleans it becomes
an operator that I've seen called "iff" and
"xnor" (exclusive not or) operator.

A B A xnor B
T T T
T F F
F T F
F F T

Why use an obscure boolean operator without a good reason?

Why use any operator without a good reason?

Good point. Use the proper tool for the job.
This is not obscure though. It is the equivalence operator, the
boolean equivalent of ==. In logic texts, it has its own symbol of a
two-headed arrow.

[snip]

Sincerely,

Gene Wirchenko

Thanks for reminding me of its proper name.

Not obscure??? I guess that's in the eye of the beholder. I don't
think I've ever encountered it in actual code; Excepting of course the
rather bizarre (and I think unintentional) usage we're discussing.

Bob S
 
?

=?iso-8859-1?Q?Nils_O=2E_Sel=E5sdal?=

I have many OR in the if statement, any method to simplify?

if (val == 5 | val == 9 | val == 34 | val == 111 | val == 131 | .......)
You want the boolean operator || , not the bitwise |
switch(val){
case 5:
case 9:
case 34:
case 111:
case 131:
do_something();
break;
}

Or use a hashtable(or just an double array) to store values/function
pointer pairs.

Or,
int testa[] = {5,9,34,111,131};

for(int i = 0 ; i< sizeof(testa);i++){
if(val == testa){
do_something();
break;
}
}

... and probably quite a few other variations also..
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,772
Messages
2,569,593
Members
45,112
Latest member
VinayKumar Nevatia
Top