473,890 Members | 2,027 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Comments are welcome for two sequential search C functions

Any comments are welcome for following the two sequential search C
functions of both integer and string versions. Though they are simple,
please do not laugh at it :) Could you give your great suggestion to
it? Thanks a lot.

/*sequentially search a array of integers for a value. val: the integer
is to be searched for in the array, array: array of integers, len: item
count in the array. return the index of the value found in array, -1
for failure. the algotithm efficience of the function is O(n). - jhl,
Jul 2006*/

#include <stddef.h>

int lookup(int val, const int array[], int len)
{
int i = -1;

if (array != NULL && len != 0){
for (i = 0; i < len; ++i){
if (val == array[i]){
break;
}
}
}
return i;
}

/*sequentially search a string array for a word. word: the word is to
be searched for in the array, array: array of word string, len: item
count in the array. return the index of the value found in array, -1
for failure. the algotithm efficience of the function is O(n). - jhl,
Jul 2006*/

#include <string.h>

int slookup(const char *word, const char *array[], int len)
{
int i = -1;

if (word != NULL && array != NULL && len != 0){
for (i = 0; i < len; ++i){
if (strcmp(word, array[i]) == 0){
break;
}
}
}
return i;
}

Jul 9 '06
31 2215
Eric Sosman wrote:
August Karlstrom wrote:
>Joe Wright wrote:
>>Using break; is ugly. Consider..

int lookup(int val, const int array[], int len)
{
int i, ret = -1;
if (array != NULL && len 0) {
for (i = 0; i < len; ++i) {
if (val == array[i]) {
ret = i; /* set the return value */
i = len; /* kill the for loop */
}
}
}
return ret;
}


I think a while-loop is even clearer:

int lookup(int val, const int array[], int len)
{
int i, ret = -1;
if (array != NULL && len 0) {
i = 0;
while ((i < len) && (val != array[i])) {
i++;
}
if (val == array[i]) {
ret = i;
}
}
return ret;
}

It might be clearer, but it's also wrong. On any
unsuccessful search, the loop terminates with i==len.
Then the test val==array[i] gives undefined behavior due
to the out-of-bounds array index.
Yes, of course. How careless of me. It should be:

int lookup(int val, const int array[], int len)
{
int i, ret = -1;
if (array != NULL && len 0) {
i = 0;
while ((i < len) && (val != array[i])) {
i++;
}
if (i < len) {
ret = i;
}
}
return ret;
}
August
Jul 10 '06 #21
Keith Thompson wrote:
Applying my advice to your code (which, of course, you're entirely
free to ignore), we get this (not tested):

/*lookup.c*/
#include <stddef.h>
int lookup(int val, const int array[], int len){
int i;

if (array != NULL && len 0){
for (i = 0; i < len; ++i){
if (val == array[i]){
return i;
}
}
}
return -1;
}
I have heard that multiple exit points makes function inline
optimization more difficult. If that is the case, the use of a result
variable might be a better choice.
August
Jul 10 '06 #22
August Karlstrom wrote:
Keith Thompson wrote:
>Applying my advice to your code (which, of course, you're entirely
free to ignore), we get this (not tested):

/*lookup.c*/
#include <stddef.h>
int lookup(int val, const int array[], int len){
int i;

if (array != NULL && len 0){
for (i = 0; i < len; ++i){
if (val == array[i]){
return i;
}
}
}
return -1;
}

I have heard that multiple exit points makes function inline
optimization more difficult. If that is the case, the use of a result
variable might be a better choice.
They can also cause logic errors if the setting of a state gets missed,
releasing a lock for example

--
Ian Collins.
Jul 10 '06 #23
August Karlstrom wrote:
Keith Thompson wrote:
>Applying my advice to your code (which, of course, you're entirely
free to ignore), we get this (not tested):

/*lookup.c*/
#include <stddef.h>
int lookup(int val, const int array[], int len){
int i;

if (array != NULL && len 0){
for (i = 0; i < len; ++i){
if (val == array[i]){
return i;
}
}
}
return -1;
}

I have heard that multiple exit points makes function inline
optimization more difficult. If that is the case, the use of a result
variable might be a better choice.
First rule of optimisation: Don't do it.
Second rule (for experts only): Don't do it yet.

Unless you have measured and found this to be a problem, use the
solution that is easier to implement correctly and easier to maintain.
Some people might choose the single exit for that reason, some might
choose the multiple exit for that reason.

In any case, this is a common enough idiom that I would be surprised if
optimisers did not handle it well.
--
Flash Gordon, living in interesting times.
Web site - http://home.flash-gordon.me.uk/
comp.lang.c posting guidelines and intro:
http://clc-wiki.net/wiki/Intro_to_clc
Jul 10 '06 #24
Richard Heathfield wrote:
(b) here is a way to write it without break:

int lookup(val, const int array[], int len)
{
int i = -1;
if(array != NULL && len != 0)
{
while(i < len && val != array[i])
And this won't try to access array[-1] ? Just goes to show, even the
most experience programmers are not immune to buffer overflows.

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/

Jul 10 '06 #25
we******@gmail. com said:
Richard Heathfield wrote:
>(b) here is a way to write it without break:

int lookup(val, const int array[], int len)
{
int i = -1;
if(array != NULL && len != 0)
{
while(i < len && val != array[i])

And this won't try to access array[-1] ?
Ouch! Nice spot.

Fortunately for my peace of mind, in my own code I clearly separate the
concepts of "output data" and "error information". The above boo-boo is a
result of trying to combine them.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jul 10 '06 #26
On Sun, 09 Jul 2006 21:13:47 GMT, Keith Thompson <ks***@mib.or g>
wrote:
>Al Balmer <al******@att.n etwrites:
[...]
>Different strokes, I guess. I find the break less ugly. In fact, not
being quite so uptight about multiple returns in tiny functions, I'd
probably write (untested)

int lookup(int val, const int array[], int len)
{
int i;
if (array != NULL && len 0) {
for (i = 0; i < len; ++i) {
if (val == array[i]) {
return i;
}
}
}
return -1;
}

In this version, the "&& len 0" is redundant. If len == 0, the loop
won't execute, and you'll fall through to the "return -1;".
(Or len < 0) Quite true, of course. I just replaced the inner loop. In
real life, I'd look a little closer, especially since the
non-idiomatic style of the original would indicate (in my environment)
a less experienced programmer.
(The
check was necessary in the original version, I think -- which is one
reason why yours is an improvement.)
--
Al Balmer
Sun City, AZ
Jul 10 '06 #27
On Mon, 10 Jul 2006 11:08:40 GMT, August Karlstrom
<fu********@com hem.sewrote:
>Keith Thompson wrote:
>Applying my advice to your code (which, of course, you're entirely
free to ignore), we get this (not tested):

/*lookup.c*/
#include <stddef.h>
int lookup(int val, const int array[], int len){
int i;

if (array != NULL && len 0){
for (i = 0; i < len; ++i){
if (val == array[i]){
return i;
}
}
}
return -1;
}

I have heard that multiple exit points makes function inline
optimization more difficult. If that is the case, the use of a result
variable might be a better choice.
<GI don't write code based on rumors about hardship for compilers.

--
Al Balmer
Sun City, AZ
Jul 10 '06 #28
Richard Heathfield <in*****@invali d.invalidwrote:
lovecreatesbeau ty said:
>Any comments are welcome for following the two sequential search C
<snip>
>#include <stddef.h>

int lookup(int val, const int array[], int len)
{
int i = -1;

if (array != NULL && len != 0){
for (i = 0; i < len; ++i){
if (val == array[i]){
break;
}
}
}
return i;
}
<snip>
(b) here is a way to write it without break:

int lookup(val, const int array[], int len)
{
int i = -1;
if(array != NULL && len != 0)
{
while(i < len && val != array[i])
{
++i;
}
if(i == len)
{
i = -1;
}
}
return i;
}
This has one of the worst kinds of UB as it will run correctly on a
wide range of systems and you probably won't even *smell* a dragon --
it just might report, sometimes, that an element is "not there" when in
fact it is.

You need, of course, to set i to 0 before asking about array[i] for
the first time (and to give a type for "val").

--
Ben.
Jul 10 '06 #29
Ben Bacarisse said:
Richard Heathfield <in*****@invali d.invalidwrote:
<a very silly bug>
This has one of the worst kinds of UB
I know, I know - very embarrassing and all that. Would you believe me if I
told you my personal code library doesn't do things that way? :-)

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jul 10 '06 #30

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

Similar topics

12
3528
by: windandwaves | last post by:
Hi Folks I have just completed a project for an accommodation finder in New Zealand - much with your help - thank you again. I would appreciate any constructive or deconstructive comments. The url is http://switch.hosts.net.nz/~admin64/index.php
38
7177
by: | last post by:
I have a script... ----- <SCRIPT language="JavaScript" type="text/javascript"> <!-- function makeArray() { for (i = 0; i<makeArray.arguments.length; i++) this = makeArray.arguments; } function makeArray0() {
15
5481
by: I. Myself | last post by:
This is about reading the .ini files which are used in several of our projects. Currently, the actual read of each line of the file is with this statement: fscanf(file, "%s %s", name, value); /* reads two strings from .ini file */ This works, but it does not allow any comments to the right of the two strings.
36
532
by: lovecreatesbeauty | last post by:
Any comments are welcome for following the two sequential search C functions of both integer and string versions. Though they are simple, please do not laugh at it :) Could you give your great suggestion to it? Thanks a lot. /*sequentially search a array of integers for a value. val: the integer is to be searched for in the array, array: array of integers, len: item count in the array. return the index of the value found in array, -1...
19
4174
by: eric.nave | last post by:
this is a slight change to a fequently asked question around here. I have a table which contains a "sortorder" column where a user can specify some arbitrary order for records to be displayed in. Users have sometimes ordered records the way we used to number lines in a BASIC program (10,20,30, etc.). I'd like to do an update query and fix this so that every record is in sequential order. I found an example in this newsgroup of how to...
2
11123
by: masker | last post by:
I was on the web trying to find a javascript that would allow me to input a number on my website and have it increase by a given percentage every second. During my search I found the Earth Population Calculator on the javascripkit.com site. The Calculator functions just as I imagine I want my number generator to function, but I need it to present a different number. I work for a non profit organization that administers Head Start and...
7
1901
by: =?Utf-8?B?V2FubmFiZQ==?= | last post by:
We are looking at Ajaxing our existing web application. Question is...Should we Ajax any and everything we can, or not? One example...if a page posts back to itself, is that a good candidate for Ajax?
12
1299
by: Phillip B Oldham | last post by:
I'm keen on learning python, with a heavy lean on doing things the "pythonic" way, so threw the following script together in a few hours as a first-attempt in programming python. I'd like the community's thoughts/comments on what I've done; improvements I can make, "don'ts" I should be avoiding, etc. I'm not so much bothered about the resulting data - for the moment it meets my needs. But any comment is welcome! #!/usr/bin/env python
5
3189
by: p3rk3le | last post by:
So, I'm about to do a sequential search on a table (n contents) of random numbers. I have to print the average between the number of comparisons and the contents of the table (n) and the average time for each sequential search. I wrote:
0
9812
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
11210
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...
0
10795
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10898
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
10444
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
8001
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
5832
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...
1
4653
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3261
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.