Question

For kicks... Problem with this snippet?

Asked by: smitty1276

Does anyone see any errors in this code snippet?  Quite clearly it is a function that returns a boolean 1 or 0 to indicate whether 2 strings are identical or not.


int streql(char *str1, char *str2)
{
   while ((*str1 == *str2) && (*str1))  
   {
      str1++;
      str2++;
   }
   return ((*str1 == NULL)  && (*str2 == NULL));
}

I'm especially interested in Axter's response.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2003-08-21 at 21:30:52ID20716893
Topic

C++ Programming Language

Participating Experts
5
Points
35
Comments
15

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Points to axter for Q20334624
    Points to axter for Q20334624
  2. Str1 & Chr(10) & Str2 problem in LotusScript R5
    I am trying to concatenate 2 strings with a LF between them (over the WEB) but it doesn't work. If I omit the Chr(10), then they concatenate ok. How can I best achieve this?

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: smitty1276Posted on 2003-08-21 at 21:32:17ID: 9200672

Does anyone see any " blatant undefined behaviour "?

 

by: knightmadPosted on 2003-08-21 at 21:53:28ID: 9200763

returns 1 if both are identical ...

It will leave the loop when the strings become different or when reach the end of str1 (then, the strings are equal, or else it would already been out of the loop because the short-circuited "and" operator)

then, we have 2 options:
1) *str1 is not null .... then, the strings are different....  (because it left the loop failing in condition *str1 == *str2)
2) *str1 is null .... then, if *str2 isn't null (str1 is an empty string and str2 not, maybe str1 == #0 and str2 == "a", for example), the strings are different, else, both are identical (they got  compared every byte before it got out of the loop with *str1 == 0.

Am I wrong?

 

by: andrewjbPosted on 2003-08-21 at 23:44:15ID: 9201178

If str1 == NULL or str2 == NULL --> Bad
if len(str2) < len(str1) -> Bad - what are you peeking at beyond the end of the string? Undefined. Also might get wrong result

 

by: knightmadPosted on 2003-08-21 at 23:52:30ID: 9201216

"if len(str2) < len(str1) -> Bad - what are you peeking at beyond the end of the string? Undefined. Also might get wrong result"
I (respectully) disagree. Will get out of the loop because (*str1 != 0) and (*str2 == 0), so (*str1 != *str2)  when we get in the end of str2 (or else, str1 == 0 mean len(str1) == len(str2)

The NULL things is right, if any of these strings is NULL, the answer is undefined (the same with strcmp, I guess, cannot compare NULL strings). My assumption was for not-null char * : ))

 

by: mayankeaglePosted on 2003-08-22 at 00:05:51ID: 9201262

You could use:

while ((*str1 == *str2) && (*str1) && (*str2))  

Sorry I didn't go through the comments above. Don't know if its already been suggested.... anyway, what is the error that you got initially?

 

by: andrewjbPosted on 2003-08-22 at 00:08:54ID: 9201271

Knightmad - I agree with myself, too. Doh. Realised, about to say sorry - notice you'd beaten me to it.... Ooops

 

by: andrewjbPosted on 2003-08-22 at 00:10:40ID: 9201277

One other comment - If you have to ask whether the function works (because it's a little 'clever' and trying to be quick) then probably don't write it like that.

Something more explicit that tests both str1 and str2 etc (e.g. mayankeagle?) might be clearer. Unless you have proved otherwise, the compiler might do just as good a job (or better!) at producing final code for you..... Don't optimise unless you know you really need to!

 

by: knightmadPosted on 2003-08-22 at 00:14:40ID: 9201292

A side-note (I'm sorry if I'm wrong)
This question seems to be a kind of "expertise test", with Axter as target
Take a look at this thread: http://www.experts-exchange.com/Programming/Programming_Languages/Cplusplus/Q_20716036.html#9200948
Just a thought ...

 

by: ManasBhattPosted on 2003-08-22 at 08:32:23ID: 9204193

If i am not mistaken, NULL is C++ means (void *). Thus it can't be used in comparing the character as such , it can just be used for comparing pointers. Thus the last statement :
 return ((*str1 == NULL)  && (*str2 == NULL));

should work.

Do let me know if  i am wrong.
thanks
-manas

 

by: ManasBhattPosted on 2003-08-22 at 08:32:38ID: 9204194

If i am not mistaken, NULL is C++ means (void *). Thus it can't be used in comparing the character as such , it can just be used for comparing pointers. Thus the last statement :
 return ((*str1 == NULL)  && (*str2 == NULL));

shouldn't work.

Do let me know if  i am wrong.
thanks
-manas

 

by: ManasBhattPosted on 2003-08-22 at 08:34:46ID: 9204213

please ignore my first posting.  i made a typo. Consider the second answer.
thanks
-manas

 

by: PhilipNicolettiPosted on 2003-08-22 at 11:04:06ID: 9205424

I didn't look at the code itself, but certainly the arguments should be "const char*"

 

by: PhilipNicolettiPosted on 2003-08-22 at 11:08:32ID: 9205465

why return an int and not a bool ?

with an int return one might "expect" that it like
strcmp() - returns -1,0,1

 

by: smitty1276Posted on 2003-08-22 at 14:39:41ID: 9206893

Because this was from a book C/C++, illustrating the types of char ptr manipulation that might occur behind the scenes in a function like strcmp().  Axter made a scene of pointing out that this book was "not recommended" by whoever, but the reviewer used this as an example of why the book was bad... and insignificant snippet showing how to iterate through 2 strings simultaneously... Here's what the reviewer had to say about it...

"Here is another example: 'Tip 173 Determining Whether Two Strings are the Same' provides you with a function to compare two strings character by character. See how many errors you can spot...  On second thoughts why bother? Either compare the addresses if you want to answer the question as phrased, or use strcmp() if you want to see if they match. Any author who can provide you with a function that includes blatant undefined behaviour when there is a perfectly good library function does not deserve to be taken seriously"

The author didn't even point out the errors he mentioned, which BTW don't exist.  I wanted Axter to justify making a show of, and even LINKING TO, this review, which is clearly biased and uninformed.  And the book does, in fact, introduce the actual strcmp() function a couple of pages later.  Heaven forbid a new programmer actually understand how to manipulate the string himself before using the prewritten one for him!  Let's not teach kids in calculus how to do calculus either... hell, they all have TI-82s that'll do it for them, right?

I'm just wondering why Axter spent the time it would have taken to go through every single persons book recommendations looking for negative reviews, how ever fraudulant they may be, to post on that thread.



 

by: knightmadPosted on 2003-08-23 at 06:23:02ID: 9208704

Nice, it seems that my side note is the correct answer to this thread ... why not to close it now?

One more comment about ManasBhatt affirmation
"If i am not mistaken, NULL is C++ means (void *). "
You're right, NULL usually is for (void *) but (altought I bet the author's idea wasn't that, it really seems to be an author's mistake) NULL == 0 in C++; if I'm not wrong, Almighty Stroustroup said this in "The C++ Programming Language"; then,

return ((*str1 == NULL)  && (*str2 == NULL));

is equivalent to

return ((*str1 == 0)  && (*str2 == 0));

smitty1276: it seems that this snippet of code will only fail for str1 == NULL or str2 == NULL, althought the "*str1 == NULL" is very obscure for begginers (maybe the "undefined behaviour" is about this obscureness. However, I'm not here to comment about this, probably you will not get Axter here to discuss this, then, in my opinion, it's time to close this thread.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...