if:
static char s2[]="Catbert";
static char s3[]= "Ratbert";
what is the vvalue of strcmp(s2, s3)<0 "Please explain"

Dani AI

Generated

Short answer: the expression is true because strcmp compares the two strings lexicographically and the first string compares as "less than" the second at the first position where they differ.

What that means in practice: strcmp returns an int whose sign indicates ordering (negative if the first string is less, zero if equal, positive if greater). The C standard only guarantees the sign, not the exact numeric value. Many implementations compute the difference between the first differing characters after converting them to unsigned char, so on typical ASCII platforms you will commonly see -15 because 'C' (67) - 'R' (82) = -15. Rely only on the sign (<0, ==0, >0) in portable code.

Use pattern for safe checks:

if (strcmp(a, b) < 0) {
    puts("a comes before b");
} else if (strcmp(a, b) > 0) {
    puts("a comes after b");
} else {
    puts("equal");
}

Notes and edge cases: if one string is a prefix of the other the shorter string is "less". For locale-aware ordering use strcoll. For case-insensitive comparisons use platform functions such as strcasecmp or _stricmp. For raw binary buffers use memcmp instead of strcmp. In short, gave the correct mechanism; ’s single-digit reply can be misleading — strcmp returns an integer whose sign matters, not necessarily the value 1.

Recommended Answers

All 2 Replies

int strcmp (const char *s1, const char *s2) - the strcmp function compares the string s1 against s2, returning a value that has the same sign as the difference between the first differing pair of characters (interpreted as unsigned char objects, then promoted to int).
In your case, "C" < "R".

>what is the vvalue of strcmp(s2, s3)<0

1

>"Please explain"

You try. We'll help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.