Solved

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

Posted on 2004-09-20
2
211 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
2 Comments
 
LVL 45

Expert Comment

by:Kdo
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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

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…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
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 while-loops in the C programming language.

746 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now