SpaceWalker
SpaceWalker

Reputation: 19

strcmp output with positive value

I read the description of strcmp it said "Tests the strings for equality. Returns a negative number if string1 is less than string2, returns zero if the two strings are equal, and returns a positive number is string1 is greater than string2" from http://www.cprogramming.com/fod/strcmp.html. however, I ran into a program that gives me positive number instead of negative number. Can anyone explain why it is positive instead of negative output?

using namespace std;

int f(int n) {
if (n < 0) {
    return -1;
} else if (n == 0) {
    return 0;
} else {
    return 1;
}
}

int main(int argc, char* argv[]) {
char a[10];
char b[10];
int n;

strcpy(a, "4");
strcpy(b, "345");

n = strcmp(a, b);
cout << f(n) << endl;
}

Upvotes: 0

Views: 755

Answers (1)

owacoder
owacoder

Reputation: 4873

strcmp() compares characters, not numerical values. "4" is greater than "345" lexicographically, hence the positive result.

Upvotes: 3

Related Questions