Search code examples
c++strcmpstring.h

compare strings with strcmp function works different


I'm comparing two strings with strcmp in the following manner:

long t=1011;
char tc[10], tcr[10];
ltoa(t,tc,10);
cout<<tc<<endl;  //prints 1011
strcpy(tcr, strrev(tc));
cout<<tcr<<endl; //prints 1101
cout<<strcmp(tc,tcr);

This gives me a result of 0, which indicates that the strings are equal. However, when I try:

cout<<strcmp("1011", "1101"); // prints -1 thats okay

I get the expected value of -1. What's am I doing wrong? I am using devc++ compiler version 4.9.9.2


Solution

  • It depends on how function strrev is defined, If it reverses the argument in place then the result is expected because tc was reversed.

    For example function strrev can be declared the following way

    char * strrev( char *s );
    

    and the return value and the value of the argument will be equal.

    Take into account that strrev is not a standard function.