- How to walk two pointers in parallel through two strings
- Why comparison stops at the first differing character
- What "lexicographic order" means and why it matters
- How
strcmpreturns a negative, zero, or positive value - The classic pitfall of comparing pointers instead of characters
How Comparison Works in Memory
Comparing two strings means walking through both of them character by character, in lockstep, and finding the first position where they differ. If you reach the end of both strings without finding a difference, they are equal. If you find a difference at some position, the string whose character has a smaller ASCII value comes "first" — that's what we call lexicographic (dictionary) order.
This is exactly what strcmp does. It takes two pointers — one to each string — and advances both while the characters they point at are equal and not yet at the terminator. When the loop exits, either both pointers are at the terminator (strings equal), or one character differs (the one with the smaller ASCII code sorts first). The return value encodes that outcome: negative, zero, or positive.
The pointer-only approach makes the parallel walk explicit. You'll use two pointers, a single while loop that advances both, and a final comparison of the two characters the pointers stopped at. No array indexing, no strlen — just pointer arithmetic.
💡 In one line: Comparison = walk two pointers side-by-side until they disagree or both hit '\0'. The sign of the first differing character's difference tells you which string comes first.
The Three Outcomes of Strcmp
| Outcome | Meaning | Return value |
|---|---|---|
*p < *q | First string comes before second | Negative number |
*p == *q == '\0' | Strings are identical | Zero |
*p > *q | First string comes after second | Positive number |
The comparison is character-based. 'A' (65) is less than 'B' (66), so "Apple" comes before "Banana". 'a' (97) is greater than 'A' (65), so "apple" comes after "Apple" — this is why case-insensitive comparison (like strcasecmp) is a separate function. And a prefix like "Hell" comes before "Hello" because the terminator ('\0', ASCII 0) is smaller than any printable character.
Complete C Program
Program: compare two strings using parallel pointer walks (implementation of strcmp)
#include <stdio.h>
/* Compare two strings lexicographically.
Returns <0 if s1 < s2, 0 if s1 == s2, >0 if s1 > s2. */
int str_compare(const char *s1, const char *s2) {
if (s1 == NULL || s2 == NULL) {
return -1; /* treat NULL as "less than" anything */
}
const char *p = s1;
const char *q = s2;
/* Walk both pointers while characters match and we haven't hit the end */
while (*p != '\0' && *q != '\0' && *p == *q) {
p++;
q++;
}
/* At this point, either *p != *q, or one/both hit '\0' */
return (unsigned char)*p - (unsigned char)*q;
}
int main(void) {
const char *a = "Apple";
const char *b = "Banana";
const char *c = "Apple";
const char *d = "App";
int r1 = str_compare(a, b);
int r2 = str_compare(a, c);
int r3 = str_compare(a, d);
printf("Compare \"%s\" vs \"%s\"\n", a, b);
if (r1 < 0) printf(" Result: \"%s\" comes before \"%s\" (r = %d)\n", a, b, r1);
else if (r1 > 0) printf(" Result: \"%s\" comes after \"%s\" (r = %d)\n", a, b, r1);
else printf(" Result: strings are equal (r = %d)\n", r1);
printf("\nCompare \"%s\" vs \"%s\"\n", a, c);
if (r2 < 0) printf(" Result: \"%s\" comes before \"%s\" (r = %d)\n", a, c, r2);
else if (r2 > 0) printf(" Result: \"%s\" comes after \"%s\" (r = %d)\n", a, c, r2);
else printf(" Result: strings are equal (r = %d)\n", r2);
printf("\nCompare \"%s\" vs \"%s\"\n", a, d);
if (r3 < 0) printf(" Result: \"%s\" comes before \"%s\" (r = %d)\n", a, d, r3);
else if (r3 > 0) printf(" Result: \"%s\" comes after \"%s\" (r = %d)\n", a, d, r3);
else printf(" Result: strings are equal (r = %d)\n", r3);
return 0;
}
Program Output
Compare "Apple" vs "Banana"
Result: "Apple" comes before "Banana" (r = -1)
Compare "Apple" vs "Apple"
Result: strings are equal (r = 0)
Compare "Apple" vs "App"
Result: "Apple" comes after "App" (r = 108)
The first comparison stops at position 0: 'A' (65) vs 'B' (66). Since 'A' < 'B', "Apple" comes first, and the function returns 65 - 66 = -1. The second comparison walks all the way through both strings — every character matches — and both hit '\0' at the same time, so the function returns 0 - 0 = 0. The third comparison walks through "App" in both strings, then p points at 'l' (108) and q points at '\0' (0). The difference is 108 - 0 = 108, a positive number, so "Apple" comes after "App".
Step-by-Step Explanation
Let's trace the pointers through the three test cases.
1. Setup
The function receives two pointers, s1 and s2, each pointing at the first character of its string. We make local copies p and q so that advancing them doesn't disturb the caller's pointers. We mark both parameters const char * because we're only reading, never writing — that also lets callers pass string literals without warnings.
2. The parallel walk
The loop condition has three parts, joined by &&:
*p != '\0'— the first string hasn't ended.*q != '\0'— the second string hasn't ended.*p == *q— the current characters are equal.
All three must be true to keep walking. The moment any one becomes false, the loop exits. That's the key insight: we stop at the first difference or at the end of either string, whichever comes first. Then one comparison at the end resolves the outcome.
3. Comparing "Apple" and "Banana"
Iteration 1: *p = 'A', *q = 'B'. They're not equal, so the third condition fails immediately. The loop body never runs. After the loop, *p = 'A' (65), *q = 'B' (66). Return 65 - 66 = -1. A negative result means the first string is lexicographically less, i.e., comes first.
4. Comparing "Apple" and "Apple"
Iterations 1–5: 'A' matches 'A', 'p' matches 'p', and so on. Both pointers advance in lockstep. Iteration 6: both *p and *q are '\0'. The first condition *p != '\0' is false, so the loop exits — we've reached the end of the first string with every character matching. After the loop, both *p and *q are '\0', so return 0 - 0 = 0. Zero means equal.
5. Comparing "Apple" and "App"
Iterations 1–3: 'A', 'p', 'p' all match; both pointers advance. Iteration 4: *p = 'l', *q = '\0'. The second condition *q != '\0' is false, so the loop exits. After the loop, *p = 'l' (108), *q = '\0' (0). Return 108 - 0 = 108. A positive result means the first string comes after the second. This makes sense: "App" is a prefix of "Apple", so it sorts first.
6. Why cast to unsigned char?
Because char may be signed on some platforms. If the bytes being compared happen to be non-ASCII (for example, accented characters or bytes from a UTF-8 sequence), a signed char would interpret bytes above 127 as negative numbers. That would make the difference calculation wrong — for example, a byte with value 200 would be treated as -56. Casting to unsigned char before subtracting gives the correct 0–255 range for each byte, so the difference is meaningful and monotonic. This is exactly what standard strcmp does internally.
7. What if the difference is larger than 1?
The function returns the actual difference between the ASCII codes, not just -1 or 1. That's why "Apple" vs "App" returns 108, not 1. The sign of the return value is what callers should rely on — negative, zero, or positive — but returning the raw difference is a common convention because it's free to compute and immediately tells you the ordering. If you only ever need the sign, you could normalize to -1/0/+1, but there's no reason to.
8. Why the NULL guard?
Dereferencing a NULL pointer is undefined behaviour — usually a crash. A strcmp-style function is typically a building block, so guarding the entry point costs very little and turns a possible segfault into a clean, predictable "less than" result. A correct caller never passes NULL, but defensive programming is a good habit for reusable code.
9. Can I write this more compactly?
Yes — the loop condition can be folded into a single expression if you're comfortable with the idiom:
while (*p && *p == *q) { p++; q++; }
return (unsigned char)*p - (unsigned char)*q;
This works because if *q is '\0' before *p is, the equality fails (one is zero, the other isn't) and the loop exits — then the final subtraction compares *p against 0. If both are '\0', the loop has already exited and returns 0. The longer form is easier to read and audit; both are correct.
10. The classic pitfall: comparing pointers
A common beginner mistake is writing if (s1 == s2) to check whether two strings are equal. That compares the pointer addresses, not the string contents. Two different arrays can contain the same characters at different addresses, so s1 == s2 would be false even though the strings are identical. Conversely, two pointers to the same array would be equal even if you wanted to compare overlapping substrings. Always compare the characters the pointers point at, which is what this function does.
11. How is this different from strcoll or case-insensitive comparison?
strcmp (and this function) compares raw byte values. That's fine for ASCII, but languages with accented characters, ligatures, or locale-specific ordering rules may sort differently than plain byte order suggests — that's what strcoll handles. And strcmp is case-sensitive: 'A' (65) is less than 'a' (97), so "abc" comes after "ABC". For case-insensitive comparison, the usual approach is to normalize both strings to the same case (using tolower) or to use a platform-specific function like strcasecmp. This function is the foundation — once you understand it, the variants are small modifications.
12. Is the input modified?
No. We only read *p and *q, never assign to them. The pointers p and q advance inside the function, but they are local copies of the caller's pointers, so the caller's variables are unaffected. Both strings are unchanged after the call. The const qualifiers on the parameters document this: the function will never write through those pointers, and the compiler will enforce it.
🎯 Remember this: Comparison walks two pointers in parallel and stops at the first difference. The sign of the difference at the stopping point tells you the lexicographic order. Use the sign, not the exact value — but do return the raw difference, as standard strcmp does.
Frequently Asked Questions
1. Why not just use strcmp?
In production code, strcmp is the standard choice — tested, portable, and likely optimized. This exercise teaches you how it works so that you can write bounded variants (strncmp), case-insensitive versions, or custom comparison rules for structures. It's also a very common interview question and a fundamental building block for sorting algorithms.
2. What does the return value mean exactly?
A negative value means the first string is lexicographically less than the second. Zero means they are equal. A positive value means the first string is greater. This mirrors the convention of strcmp and similar functions, making it easy to reuse: qsort comparators, binary search, and sort functions all expect this pattern. The exact magnitude is usually ignored — only the sign matters.
3. How does lexicographic order work for mixed-case strings?
It compares raw ASCII values, so uppercase letters (65–90) come before lowercase letters (97–122). This means "Zebra" comes before "apple" even though a dictionary would list "apple" first. That's why case-insensitive comparison is a separate operation. If you need dictionary-style ordering with case folded, convert both strings to lowercase before comparing — or use a locale-aware function like strcasecmp or strcoll.
4. Can this compare strings of different lengths?
Yes. The loop walks until either pointer reaches the terminator, so strings of different lengths are handled correctly. When one ends first, the other's remaining character (or terminator) determines the result. A prefix comes before the longer string: "car" < "cart" because '\0' (0) is less than 't' (116).
5. What is the difference between strcmp and strncmp?
strncmp takes a third argument — the maximum number of characters to compare. This is useful when comparing prefixes, or when one string might not be null-terminated within the expected bound. strcmp walks until a terminator or a mismatch, which is fine when both strings are guaranteed valid. If you're parsing untrusted input, bounded comparison is safer because it can't run off the end of a malformed buffer.
6. What if both pointers are NULL?
This function handles it by returning -1 (treating NULL as less than anything, including another NULL, so it would return 0 for two NULLs in a strict reading — but the guard short-circuits before the pointers are used). In general, passing NULL to a string function is a programming error, not a case to design around. The guard is a safety net, not a contract.
💡 Tip: After this works, try implementing strncmp — the same loop, but with a size_t n counter that decrements on each iteration and stops the loop when it hits zero. It's a small change that makes the function safe for comparing prefixes and bounded input, and it's a natural next step.