Why is my implementation of strcmp not returning the proper value?

Posted by Avanish Giri on Stack Overflow See other posts from Stack Overflow or by Avanish Giri
Published on 2012-06-20T08:48:56Z Indexed on 2012/06/20 9:16 UTC
Read the original article Hit count: 243

Filed under:
|

Why is this printing out 0 back in main but 6 when it is inside of the strcmp function?

  7 int main()
  8 {
  9 char* str = "test string";
 10 char* str2 = "test strong";
 11 //printf("string length = %d\n",strlen(str));
 12 
 13 int num = strcmp(str,str2);
 14 
 15 printf("num = %d\n",num);
 16 }




 29 int strcmp(char* str, char* str2)
 30 {
 31   if(*str == '\0' && *str2 == '\0')
 32     return 0;
 33   if(*str2 - *str == 0)
 34   {
 35     strcmp(str+1,str2+1);
 36   }
 37   else
 38   {
 39     int num = *str2 - *str;
 40     cout << "num = " <<num<<endl;
 41     return num;
 42     }
 43 }

The output is:

num = 6 num = 0

Why is it printing 0 when obviously the value that it should be returning is 6?

© Stack Overflow or respective owner

Related posts about c++

Related posts about c