Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What causes strcmp to return a value other than 0, 1, or -1?

I have this piece of code. When I run it, it returns 13, -13, and 0.
Isn’t it supposed to return 1 if the str1 is greater than str2 and -1 if str1 is less than str2.

I get 13, -13 and 0.

#include <iostream>
#include <string>
#include <cstring>

int main() {

    char str1[] = "Megadeth";
    char str2[] = "Metallica";

    // Should return -1 because "Megadeth" < "Metallica" lexicographically
    int result = strcmp(str1, str2);

    std::cout << "Comparing " << str1 << " and " << str2 << ": " << result << std::endl;

    // Should return 1 because "Metallica" > "Megadeth" lexicographically
    result = strcmp(str2, str1);

    std::cout << "Comparing " << str2 << " and " << str1 << ": " << result << std::endl;

    // Should return 0 because "Megadeth" = "Megadeth" lexicographically
    result = strcmp(str1, str1);

    std::cout << "Comparing " << str1 << " and " << str1 << ": " << result << std::endl;

    return 0;
}

Here is the result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Comparing Megadeth and Metallica: -13
Comparing Metallica and Megadeth: 13
Comparing Megadeth and Megadeth: 0

I’ve just followed a tutorial on the Internet and they say it’s supposed to return ones. I don’t know what is causing this.

>Solution :

strcmp is not defined to return 1, 0, or -1. The result is either positive if the first is lexicographically greater than the second, negative if the first is lexicographically less than the second, or 0 otherwise. Only the sign, or 0, are defined, not the magnitude.

man strcmp:

The strcmp() and strncmp() functions return an integer greater than, equal to, or less than 0, according as the string s1 is greater than, equal to, or less than the string s2. The comparison is done using unsigned characters, so that ‘\200′ is greater than `\0’.

Letters that come first, at least on your implementation, are considered ‘smaller.’ So the first letter to mismatch between Megadeth and Metallica is the g versus the t. t is greater than g so when Metallica is second, the result is negative.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading