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

  #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;
Who is Participating?
brettmjohnsonConnect With a Mentor Commented:
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)

Kent OlsenData Warehouse Architect / DBACommented:

Try changing the check to this:

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

You want to increment the pointer, not the data.


Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.