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?
Did you forget to add a
returnstatement?Otherwise, the code will just skip past the rest of your
ifstatement and reach the end of your function, returning nothing (or0in 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
voidfromnon voidfunction. If not, you should compile with-Wall🙂