473,890 Members | 1,370 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to simplify many OR in if statement?

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
22 17115
"Alan" <al************ *@sinatown.com> wrote in message news:<bs******* ***@news.hgc.co m.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
Ron Natalie wrote:
"Mike Hewson" <he******@austa rnet.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
In article <bs**********@n ews.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
"Ron Natalie" <ro*@sensor.com > wrote in message
news:3f******** **************@ news.newshostin g.com...

"Mike Hewson" <he******@austa rnet.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
"Keith Thompson" <ks***@mib.or g> wrote in message
news:ln******** ****@nuthaus.mi b.org...
Jeff Schwab <je******@comca st.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
Jeff Schwab <je******@comca st.net> writes:
Keith Thompson wrote:
Jeff Schwab <je******@comca st.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_Keit h) 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
"Jeff Schwab" <je******@comca st.net> wrote in message
news:65******** ************@co mcast.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
In article <ln************ @nuthaus.mib.or g>,
Keith Thompson <ks***@mib.or g> wrote:
Jeff Schwab <je******@comca st.net> writes:
Keith Thompson wrote:
Jeff Schwab <je******@comca st.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

Bob S

On Tue, 23 Dec 2003 18:57:40 GMT, Keith Thompson <ks***@mib.or g> wrote:
Jeff Schwab <je******@comca st.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_ar ray[val] == true" is clearer, you should
think that "(boolean_a rray[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_Keit h) 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
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

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2123
by: dmiller23462 | last post by:
Hey guys.... I put an error-handling in my page and have it posted at the complete end of the code, see below(when people were putting in 's I was getting the delimiter errors). Great, I understand that now and it seems to be fixed but the data I'm pulling from the HTML fields is not being appended correctly do my Access DB....The field in the DB now reads " ' ". I understand why it does that (my function) but what I need it to read is...
22
1776
by: Alan | last post by:
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
11
50389
by: Colleyville Alan | last post by:
I posted that I was having trouble with a SQL statement that was working in the SQL window, but not in VBA. I have since discovered that when I create the string in VBA it is over 1023 characters long. When I copy this string into the SQL window, it splits into two lines, one of 1023 and the remainder in the next. When I remove that break, the query runs just fine. Since Access tells me that a string can hold 10^16 (64k), it did not...
37
3328
by: Steven Bethard | last post by:
The PEP below should be mostly self explanatory. I'll try to keep the most updated versions available at: http://ucsu.colorado.edu/~bethard/py/pep_create_statement.txt http://ucsu.colorado.edu/~bethard/py/pep_create_statement.html PEP: XXX Title: The create statement
18
2734
by: Steven Bethard | last post by:
I've updated the PEP based on a number of comments on comp.lang.python. The most updated versions are still at: http://ucsu.colorado.edu/~bethard/py/pep_create_statement.txt http://ucsu.colorado.edu/~bethard/py/pep_create_statement.html In this post, I'm especially soliciting review of Carl Banks's point (now discussed under Open Issues) which asks if it would be better to have the create statement translated into:
28
2967
by: Steven Bethard | last post by:
Ok, I finally have a PEP number. Here's the most updated version of the "make" statement PEP. I'll be posting it shortly to python-dev. Thanks again for the previous discussion and suggestions! PEP: 359 Title: The "make" Statement Version: $Revision: 45366 $ Last-Modified: $Date: 2006-04-13 07:36:24 -0600 (Thu, 13 Apr 2006) $
7
2709
by: Steven Bethard | last post by:
I've updated PEP 359 with a bunch of the recent suggestions. The patch is available at: http://bugs.python.org/1472459 and I've pasted the full text below. I've tried to be more explicit about the goals -- the make statement is mostly syntactic sugar for:: class <name> <tuple>: __metaclass__ = <callable>
3
2055
by: Don | last post by:
Hi, I would like my users to be able to enter STARTDATE and leave the ENDDATE open in the query by form that I have built. Using some code from another group post I have this within my SQL statement: strMySQL = strMySQL & "And ((Forms.frmMainSearch.STARTDATE Is Null) Or (Forms.frmMainSearch.ENDDATE Is Null)" & vbCrLf strMySQL = strMySQL & "Or (.COLLDATE BETWEEN Forms.frmMainSearch.STARTDATE AND...
1
6086
AmLegacy
by: AmLegacy | last post by:
I'm having a hard time figuring out how to simplify the fractions. Can anyone look at this code and see if you can see something I don't. //This is the fraction adding function void add_fractions (int a, int b, int c, int d, int *ansn, int *ansd) { //int e, x, y, rem, gcd; a = a*d; //numerator 1 * denominator 2 c = c*b; //numerator 2 * denominator 1 b = b*d; // denominator 1 * denominator 2 d = b; //denominator 2 = denominator 1
2
3165
by: francismariani | last post by:
I'm sorry to post this complex SQL statement - I'm trying to simplify it. SELECT CASE WHEN SYS1.S1_CL_MG_ACT_D.OWN_RESP_NODE_CD IN ('D2192', 'D3155', 'D3211', 'D3212', 'D3213', 'D3214', 'D3215', 'D3216', 'D3217', 'D3218', 'D3220', 'D3222', 'D3325', 'D3334', 'D3335', 'D3337', 'D3338', 'D3424', 'D3425', 'D3488', 'D3600', 'D3739', 'D3744', 'D3745',
0
9826
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11236
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10925
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9641
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8018
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7172
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5855
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
4276
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3283
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.