Solved

Print's that 'e' is the least char. why doesn't this work?

Posted on 2004-09-20
2
245 Views
Last Modified: 2010-04-15
 
  #define LEAST(x,y) ((x) < (y) ? (x) : (y))

   char *puzzle = "A real puzzle";
   int main()
  {
      int least=10000;
      char *p = puzzle;       

      while( *p  )              
           least = LEAST( least, *p++ );              
     
      printf( "The least char is '%c'\n", least );
      return 0;
  }
0
Comment
Question by:ccooney
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 45

Expert Comment

by:Kent Olsen
ID: 12106691


Try changing the check to this:

     while( *p  )            
           least = LEAST(least, *(p++));            


You want to increment the pointer, not the data.


Kent

0
 
LVL 23

Accepted Solution

by:
brettmjohnson earned 250 total points
ID: 12106992
There are several problems with this code:

1) Beware of macro side effects.  Notice that after the macro substitution the code is
          least = ((least) < (*p++) ? (least) : (*p++));

Notice that p gets incremented twice, once in the test, and again if the test fails.


2) When comparing characters, the ASCII collating order is observed.  In the string
"A real puzzle", the space character would be considered "least" by this definition.
(space has the ASCII code 32 whereas 'e' has ASCII code 101)

0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.

690 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question