?
Solved

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

Posted on 2004-09-20
2
Medium Priority
?
248 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 46

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 1000 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

Industry Leaders: 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

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.
Suggested Courses
Course of the Month9 days, 19 hours left to enroll

762 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