-3

Will someone please explain this code in details and why 0 is coming?

Source Code:

#include<stdio.h>
void main(){
char *str="Hello";
char *ptr = str;
char least =127;
while (*ptr++)
    least = ((*ptr)<(least))?(*ptr):(least);
printf("%d", least);
}

Output:

0
Arnab
  • 19
  • 2
  • 2
    `*ptr` is `'\0'`. (in last of string) – BLUEPIXY Sep 12 '16 at 02:52
  • Possible duplicate of [Does \*p++ increment after dereferencing?](http://stackoverflow.com/questions/9255147/does-p-increment-after-dereferencing) – 001 Sep 12 '16 at 03:13

2 Answers2

4

It looks like you're trying to find the smallest ASCII value in a string.

The problem with your code is that the while() loop ignores the first byte of the string and looks at the '\0' end-of-string marker instead. What you want to do is exit the loop before you compare least with zero.

Try this instead:

while (*ptr) {
    least = ((*ptr)<(least))?(*ptr):(least);
    ptr++;
}
r3mainer
  • 23,981
  • 3
  • 51
  • 88
  • Actually, It was MCQ type question in a paper and Asked for the output. I came to know the answer when I ran it on my machine but I have no idea how it came. That is why I asked you to explain. – Arnab Sep 14 '16 at 11:03
1

All of your problems are caused by obfuscation - trying to write a simple algorithm as complicated as possible (bad programming). This does not only cause the mentioned bug(s) but also reduces readability and performance.

Had you tried to write the simple algorithm as simple as possible (good programming), there would have been no problems and the code would also execute faster:

#include <stdio.h>
#include <limits.h>

int main (void)
{
  const char* str="Hello";
  char least = CHAR_MAX;

  for(size_t i=0; str[i] != '\0'; i++)
  {
    if(str[i] < least)
    {
      least = str[i];
    }
  }

  printf("%c = %d", least, least);
}
Lundin
  • 195,001
  • 40
  • 254
  • 396
  • Actually, It was MCQ type question in a paper and Asked for the output. I came to know the answer when I ran it on my machine but I have no idea how it came. That is why I asked you to explain. – Arnab Sep 14 '16 at 11:05