Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

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?

like image 942
ordinary Avatar asked Jun 20 '12 08:06

ordinary


2 Answers

Did you forget to add a return statement?

 33 if(*str2 - *str == 0)
 34   {
 35     return strcmp(str+1,str2+1);
 36   }

Otherwise, the code will just skip past the rest of your if statement and reach the end of your function, returning nothing (or 0 in your case, but that's being lucky).

Your code will only work if the first characters of both strings are different from each other. Or if both strings are empty.

Your compiler should warn you about this; returning void from non void function. If not, you should compile with -Wall :)

like image 93
Ja͢ck Avatar answered Oct 19 '22 20:10

Ja͢ck


This is the problem:

if(*str2 - *str == 0)
{ 
    strcmp(str+1,str2+1); /* no return here. */
}

meaning the code will drop through to end, where there is no return, which is undefined behaviour:

  • From section 6.9.1 Function definitions of the C99 standard:

If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.

  • From section 6.6.3 The return statement of the C++03 standard:

Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.

As the behaviour is undefined anything can occur. In this case 0 is returned.

Change to:

if(*str2 - *str == 0)
{ 
    return strcmp(str+1,str2+1);
}
like image 21
hmjd Avatar answered Oct 19 '22 21:10

hmjd