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
Solved

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

Posted on 2004-09-20
2
232 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: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

Enterprise Mobility and BYOD For Dummies

Like “For Dummies” books, you can read this in whatever order you choose and learn about mobility and BYOD; and how to put a competitive mobile infrastructure in place. Developed for SMBs and large enterprises alike, you will find helpful use cases, planning, and implementation.

Question has a verified solution.

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

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
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…
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.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.

860 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