By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,421 Members | 1,128 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,421 IT Pros & Developers. It's quick & easy.

how to simplify many OR in if statement?

P: n/a
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
Nov 14 '05 #1
Share this Question
Share on Google+
22 Replies


P: n/a

"Alan" <al*************@sinatown.com> schrieb im Newsbeitrag
news:bs**********@news.hgc.com.hk...
I have many OR in the if statement, any method to simplify?

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


ITYM
if(val == 5 || val == 9......

If there is no systematic in the values of val, the only thing I can think
of is a switch:

switch(val)
{
case 5:
case 9:
case 34:
....
case 234:
<do your stuff here>
break;
}

But I'd rethink the approach if it requires such a mass of or's

Robert
Nov 14 '05 #2

P: n/a
Alan wrote:
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


Please don't cross-post.

I assume you want to be able to do something like this:

int main( )
{
int var = 3; // Initialize to whatever...

if( in_set( var ) )
{
// ...
}
}

The long "or" statement is not a bad way to go, unless you have a
really, really large set of numbers to check. Here is a couple of
alternatives:

/* C or C++ */

int in_set( int i )
{
int result = 0;

switch( i )
{
case 5:
case 9:
case 34:
case 111:
case 131:
result = 1;
}

return result;
}
/* C++ only */

namespace
{
int values[ ] = { 5, 9, 34, 111, 131 /* , ... */ };
int num_values = sizeof values / sizeof *values;

std::set< int > value_set( values, values + num_values );

inline bool in_set( int i )
{
return value_set.find( i ) != value_set.end( );
}
}

Nov 14 '05 #3

P: n/a
"Alan" <al*************@sinatown.com> wrote in message
news:bs**********@news.hgc.com.hk...
I have many OR in the if statement, any method to simplify?

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


Don't know of any evident simplification, assuming the logic of the
problem actually *requires* some common code to be executed for those many
different values of 'val'.

One can *restate* using De Morgan's theorem:

if( !(val <> 5 && val <> 9 && val <> 34 && val <> 111 && val <> 131 &&
........) )
// Common code.

which flicks the OR's, but alas no more simply!

You could create a boolean array, and use val as an index for it, with
the array elements indicating a 'yes' for 5,9,34,111,131...... ( and 'no'
otherwise ).

if( boolean_array[val] == true )
// Common code.

but then one also needs memory for the array, and some initialization of
it's contents to boot.

What is the context of your logical expression?

--

Cheers
--
Hewson::Mike
"This letter is longer than usual because I lack the time to make it
shorter" - Blaise Pascal
Nov 14 '05 #4

P: n/a
In comp.lang.c Jeff Schwab <je******@comcast.net> wrote:
Please don't cross-post.
You mean "Please cross-post carefully." comp.lang.c++ was clearly not
warranted, but there's nothing wrong with this going to acllcc++...

switch( i )
{
case 5:
case 9:
case 34:
case 111:
case 131:
result = 1;
}


I rather prefer this method myself, FWIW.

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Nov 14 '05 #5

P: n/a

"Mike Hewson" <he******@austarnet.com.au> wrote in message news:bs************@ID-135553.news.uni-berlin.de...

if( !(val <> 5 && val <> 9 && val <> 34 && val <> 111 && val <> 131 &&


And what language is this? Looks like some mutant cross between C++ and Fortran.

Nov 14 '05 #6

P: n/a
"Ron Natalie" <ro*@sensor.com> wrote in message
news:3f**********************@news.newshosting.com ...

"Mike Hewson" <he******@austarnet.com.au> wrote in message news:bs************@ID-135553.news.uni-berlin.de...

if( !(val <> 5 && val <> 9 && val <> 34 && val <> 111 && val <> 131
&&
And what language is this? Looks like some mutant cross between C++ and Fortran.


It's that De Morgan guy. Couldn't program his way out of a paper bag.

--
Cy
http://home.rochester.rr.com/cyhome/
Nov 14 '05 #7

P: n/a
Christopher Benson-Manica wrote:
In comp.lang.c Jeff Schwab <je******@comcast.net> wrote:

Please don't cross-post.

You mean "Please cross-post carefully." comp.lang.c++ was clearly not
warranted, but there's nothing wrong with this going to acllcc++...


Right you are!
switch( i )
{
case 5:
case 9:
case 34:
case 111:
case 131:
result = 1;
}

I rather prefer this method myself, FWIW.


I would like this if I knew a suitable jump-table would be generated in
the code, but for such disparate values... Anyway, I actually *did*
like Mike's suggestion of creating an array of boolean values:

if( boolean_array[val] == true )
// Common code.
-Jefff

Nov 14 '05 #8

P: n/a
Jeff Schwab <je******@comcast.net> writes:
[...]
I would like this if I knew a suitable jump-table would be generated
in the code, but for such disparate values... Anyway, I actually
*did* like Mike's suggestion of creating an array of boolean values:

if( boolean_array[val] == true )
// Common code.


Even assuming you have an appropriate definition for "true", the
comparison is unnecesary. In general, explicitly comparing boolean
values to "true" or "false" is unnecessary and potentially dangerous.
It's already a boolean, after all.

C (unless you have C99) has no predefined boolean type. In both C and
C++, any non-zero integer value is considered true in a condition; if
your "true" is defined as 1, the comparison will fail for any value
other than 0 or 1.

Just use

if ( boolean_array[val] ) {
/* blah blah */
}

(If you think that "boolean_array[val] == true" is clearer, you should
think that "(boolean_array[val] == true) == true" is even clearer.)

Note that this argument doesn't apply to non-boolean values used as
conditions. A pointer value, for example, can be used as a condition
(implicitly testing whether it's a null pointer), but many programmers
prefer to make the comparison explicit; "if (p)" and "if (p != NULL)"
are equally valid.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
(Note new e-mail address)
Nov 14 '05 #9

P: n/a
Keith Thompson wrote:
Jeff Schwab <je******@comcast.net> writes:
[...]
I would like this if I knew a suitable jump-table would be generated
in the code, but for such disparate values... Anyway, I actually
*did* like Mike's suggestion of creating an array of boolean values:

if( boolean_array[val] == true )
// Common code.

Even assuming you have an appropriate definition for "true", the
comparison is unnecesary. In general, explicitly comparing boolean
values to "true" or "false" is unnecessary and potentially dangerous.
It's already a boolean, after all.


I agree completely; I was copying someone Mike's code. Anyway, I see
nothing inherently wrong with "== true," even though I prefer to skip it.
Note that this argument doesn't apply to non-boolean values used as
conditions. A pointer value, for example, can be used as a condition
(implicitly testing whether it's a null pointer), but many programmers
prefer to make the comparison explicit; "if (p)" and "if (p != NULL)"
are equally valid.


That's exactly the same situation. I also prefer "if( p )" to "if p !=
NULL )," but I see no need to be religious about it. The one that
really bugs me is seeing someone "correct" this:

if( p == NULL )

to this:

if( NULL == p )

This is supposed to help avoid accidental assignment in the test.
However, I think "if( p )" avoids the same problem in a much shorter,
more readable way.

Anway, different key-strokes for different folks, I guess.

-Jeff

Nov 14 '05 #10

P: n/a
"Alan" <al*************@sinatown.com> wrote in message news:<bs**********@news.hgc.com.hk>...
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


First of all, I think you want the logical OR operator || instead of
the bitwise OR operator |. Other than that...

Personally, I would put this test into its own function.

#ifndef TRUE
#define TRUE (1)
#define FALSE (0)
#endif
...
int valueInSet (int val, int *set, int setsize)
{
int i;

for (i = 0; i < setsize; i++)
{
if (val == set[i])
return TRUE;
}

return FALSE;
}

int main (void)
{
int testSet[] = {5, 9, 34, 111, 131, ...};
int setSize = (int) (sizeof testSet / sizeof testSet[0]);
int val;
...
if (valueInSet (val, testSet, setSize))
{
/* do something */
}
...
return 0;
}

Yes, it introduces a bit more overhead than just writing out the test
longhand (either using the sequential OR approach or by using the
switch structure others have suggested). The tradeoff is that this
solution is more general. If your test set changes, you don't have to
actually muck with the program logic, just the contents of the test
set.

With some time I could probably come up with something a bit more
clever, but I think this is a good solution.
Nov 14 '05 #11

P: n/a
Ron Natalie wrote:
"Mike Hewson" <he******@austarnet.com.au> wrote in message news:bs************@ID-135553.news.uni-berlin.de...
if( !(val <> 5 && val <> 9 && val <> 34 && val <> 111 && val <> 131 &&


And what language is this? Looks like some mutant cross between C++ and Fortran.

C mixed up with Pascal, Basic or some other language which uses <> for
the inequality operator.

It should be rather:
if( !(val != 5 && val != 9 && val != 34 && val != 111 &&/*etc*/

--
Ro*************@rbdev.net
Nov 14 '05 #12

P: n/a
In article <bs**********@news.hgc.com.hk>,
"Alan" <al*************@sinatown.com> wrote:
I have many OR in the if statement, any method to simplify?

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


Have a look at the || operator.
Nov 14 '05 #13

P: n/a
"Ron Natalie" <ro*@sensor.com> wrote in message
news:3f**********************@news.newshosting.com ...

"Mike Hewson" <he******@austarnet.com.au> wrote in message news:bs************@ID-135553.news.uni-berlin.de...

if( !(val <> 5 && val <> 9 && val <> 34 && val <> 111 && val <> 131
&&
And what language is this? Looks like some mutant cross between C++ and

Fortran.

Whoops, my brain fart, sorry!
I was doing VBScripting at the time, and slipped a cog reloading the old
task state segment.
( grumble ..Damned multitasking....grumble ).

Happy to have amused you all, though :-)

--

Cheers
--
Hewson::Mike
"This letter is longer than usual because I lack the time to make it
shorter" - Blaise Pascal
Nov 14 '05 #14

P: n/a
"Keith Thompson" <ks***@mib.org> wrote in message
news:ln************@nuthaus.mib.org...
Jeff Schwab <je******@comcast.net> writes:
[...]
I would like this if I knew a suitable jump-table would be generated
in the code, but for such disparate values... Anyway, I actually
*did* like Mike's suggestion of creating an array of boolean values:

if( boolean_array[val] == true )
// Common code.
Even assuming you have an appropriate definition for "true", the
comparison is unnecesary.


Sorry ( again ), I meant to write 'yes' - meaning whatever one had coded in
the array as being that.
In general, explicitly comparing boolean values to "true" or "false" is

unnecessary and potentially > dangerous.

Indeed, please tell.....

--

Cheers
--
Hewson::Mike
"This letter is longer than usual because I lack the time to make it
shorter" - Blaise Pascal
Nov 14 '05 #15

P: n/a
Jeff Schwab <je******@comcast.net> writes:
Keith Thompson wrote:
Jeff Schwab <je******@comcast.net> writes:
[...]
I would like this if I knew a suitable jump-table would be generated
in the code, but for such disparate values... Anyway, I actually
*did* like Mike's suggestion of creating an array of boolean values:

if( boolean_array[val] == true )
// Common code.

Even assuming you have an appropriate definition for "true", the
comparison is unnecesary. In general, explicitly comparing boolean
values to "true" or "false" is unnecessary and potentially dangerous.
It's already a boolean, after all.


I agree completely; I was copying someone Mike's code. Anyway, I see
nothing inherently wrong with "== true," even though I prefer to skip
it.


Any non-zero value is considered true. Assuming that "true" is
defined as 1, and "b" has the value 2, the condition (b) is true, but
(b == true) is false.

Even if you're working in a language like C99 or C++ that has an
actual boolean type, there are still a lot of legacy functions that
return integer values, such as the is* functions in <ctype.h>.
There's no requirement that isalpha(), for example, has to return
either 0 or 1.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
(Note new e-mail address)
Nov 14 '05 #16

P: n/a
"Jeff Schwab" <je******@comcast.net> wrote in message
news:65********************@comcast.com...
I would like this if I knew a suitable jump-table would be generated in
the code, but for such disparate values... Anyway, I actually *did*
like Mike's suggestion of creating an array of boolean values:

if( boolean_array[val] == true )
// Common code.


After I posted, I saw yours and liked it better! :-)
A question is, I guess, what is the number of 'hits' you want in the
test compared to the range of possible values of 'val' ( it's type, but be
careful here ). If it's 5 out of 65536 I'm wasting alot array, so better to
just keep a list of the hits as per Jeff.

To the OP, please dive in any time here and let us know what the context
of the test is!

--

Cheers
--
Hewson::Mike
"This letter is longer than usual because I lack the time to make it
shorter" - Blaise Pascal
Nov 14 '05 #17

P: n/a
In article <ln************@nuthaus.mib.org>,
Keith Thompson <ks***@mib.org> wrote:
Jeff Schwab <je******@comcast.net> writes:
Keith Thompson wrote:
Jeff Schwab <je******@comcast.net> writes:
[...]
>I would like this if I knew a suitable jump-table would be generated
>in the code, but for such disparate values... Anyway, I actually
>*did* like Mike's suggestion of creating an array of boolean values:
>
> if( boolean_array[val] == true )
> // Common code.
Even assuming you have an appropriate definition for "true", the
comparison is unnecesary. In general, explicitly comparing boolean
values to "true" or "false" is unnecessary and potentially dangerous.
It's already a boolean, after all.


I agree completely; I was copying someone Mike's code. Anyway, I see
nothing inherently wrong with "== true," even though I prefer to skip
it.


Any non-zero value is considered true. Assuming that "true" is
defined as 1, and "b" has the value 2, the condition (b) is true, but
(b == true) is false.

Even if you're working in a language like C99 or C++ that has an
actual boolean type, there are still a lot of legacy functions that
return integer values, such as the is* functions in <ctype.h>.
There's no requirement that isalpha(), for example, has to return
either 0 or 1.


The worst case is debugging: You have a program, and you know (by
testing) that under certain circumstances it produces the wrong results.
So you look at code to find which bits of code look like they could go
wrong. In that situation, when you spot

if( boolean_array[val] == true ) ...

you will have to check that "true" is equal to 1 and that the values
stored in boolean_array are always either 0 to 1. If you write

if( boolean_array[val] )

you can save your time. (Note that I expect code to be written by
reasonably competent programmers, and a reasonably competent programmer
would only compare a "boolean" value to true if there are possibilities
other than 0 or 1. As a result, either the comparison "== true" will be
removed after a lengthy check of surrounding code, or a comment will be
added that values other than 0 or 1 are expected).
Nov 14 '05 #18

P: n/a

Bob S

On Tue, 23 Dec 2003 18:57:40 GMT, Keith Thompson <ks***@mib.org> wrote:
Jeff Schwab <je******@comcast.net> writes:
[...]
I would like this if I knew a suitable jump-table would be generated
in the code, but for such disparate values... Anyway, I actually
*did* like Mike's suggestion of creating an array of boolean values:

if( boolean_array[val] == true )
// Common code.


Even assuming you have an appropriate definition for "true", the
comparison is unnecesary. In general, explicitly comparing boolean
values to "true" or "false" is unnecessary and potentially dangerous.
It's already a boolean, after all.

C (unless you have C99) has no predefined boolean type. In both C and
C++, any non-zero integer value is considered true in a condition; if
your "true" is defined as 1, the comparison will fail for any value
other than 0 or 1.

Just use

if ( boolean_array[val] ) {
/* blah blah */
}

(If you think that "boolean_array[val] == true" is clearer, you should
think that "(boolean_array[val] == true) == true" is even clearer.)

Note that this argument doesn't apply to non-boolean values used as
conditions. A pointer value, for example, can be used as a condition
(implicitly testing whether it's a null pointer), but many programmers
prefer to make the comparison explicit; "if (p)" and "if (p != NULL)"
are equally valid.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
(Note new e-mail address)

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?

I agree with Jeff that an array of boolean values (perhaps a
bit vector) indexed by the value being tested is a little
better than a switch statement. With the array you can pretty well
predict what code will be generated by the compiler. With
a switch statement you don't know. Of course if the code
isn't critical or the number of values you're searching
through is small it doesn't really matter which of the three
techniques you use.

I did work on one memorable program that had an if statement
that was doing this sort of test. The condition portion of
the if statement literally took an entire page of blue bar
(60 lines by 80 characters) even though it was formatted
to use the minimum number of characters. White space?
Doesn't the compiler just ignore it anyway? :-)

If the number of values that you are searching for is large,
then or'ing together a lot of tests is not a good idea. At
that point it becomes a hard-coded sequential search. Actually,
ORing more than about 4 or 5 values is pretty cleary
just a hard-coded sequential search.

Bob S
Nov 14 '05 #19

P: n/a
On 23 Dec 2003 20:13:53 EST, po*********************@yahoo.com (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?

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

Nov 14 '05 #20

P: n/a
On Tue, 23 Dec 2003 17:56:27 +0800, Alan wrote:
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 }
--
Help Support Independent Film
- http://www.cafepress.com/popcornfilms
- http://www.popcornfilms.com/
Nov 14 '05 #21

P: n/a

On Wed, 24 Dec 2003 17:06:27 GMT, Gene Wirchenko <gw**************@CAPITALSwencomine.com> wrote:
On 23 Dec 2003 20:13:53 EST, po*********************@yahoo.com (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

Nov 14 '05 #22

P: n/a
In article <bs**********@news.hgc.com.hk>, Alan wrote:
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[i]){
do_something();
break;
}
}

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

--
Nils Olav Selåsdal <NO*@Utel.no>
System Developer, UtelSystems a/s
w w w . u t e l s y s t e m s . c o m

Nov 14 '05 #23

This discussion thread is closed

Replies have been disabled for this discussion.