Pointer Assignment 22 — Compare Two Strings Using a Function and Pointers
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Compare Two Strings Using Pointers — Character-by-Character Walk with Early Exit

📑 On this page:
  • How Pointer-Based String Comparison Works
  • The Three Steps of the Comparison
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How two pointers walk two strings in lockstep, comparing characters
  • Why comparison stops on the first mismatch — no need to look further
  • Why returning the raw character difference (not just -1/0/+1) matches strcmp
  • How to use unsigned char casts to avoid sign-extension bugs
  • What lexicographic ordering means and how null terminators end the walk

How Pointer-Based String Comparison Works

Comparing two strings means asking: are they identical, and if not, which one comes first in alphabetical order? The standard answer — and the one C uses with strcmp — is lexicographic order: compare the first characters; if they differ, the string with the smaller character is smaller. If they match, compare the second characters, then the third, and so on. The first position where they differ decides the result. If all characters match and both strings end at the same time, they are equal.

With pointers, the comparison is naturally expressed as a lockstep walk. Let a point at the first character of s1 and b at the first character of s2. On each iteration, compare *a with *b. If they differ, the difference (*a - *b) tells you which string is smaller — and also serves as the return value, matching strcmp. If they're equal, advance both pointers and continue. Stop as soon as one of them is the null terminator, because that means at least one string has ended.

The loop condition while (*a != '\0' && *a == *b) captures both stopping conditions in one line. If *a is the null terminator, the loop stops — either because both strings ended (*b is also '\0', so they're equal) or because s1 ended first (so s1 is the shorter string, hence smaller). If *a == *b is false before the null terminator, the characters differ — that's the decisive position. In both cases, the final values of *a and *b determine the answer.

💡 In one line: Walk both strings with two pointers, comparing character by character; the first mismatch decides the result, and if no mismatch occurs before both strings end, they're equal.

Diagram showing two pointers walking two strings in lockstep, comparing characters one by one until a mismatch or a null terminator is found

The Three Steps of the Comparison

Step Pointer operation Effect
1. Set up the pointersconst unsigned char *a = s1, *b = s2;Each pointer starts at the first character of its string
2. Walk while matchingwhile (*a != '\0' && *a == *b) { a++; b++; }Both pointers advance in lockstep as long as characters are equal and neither string has ended
3. Return the differencereturn *a - *b;0 if equal, positive if s1 > s2, negative if s1 < s2

The return convention is worth understanding, because it's easy to get wrong. strcmp doesn't return just -1, 0, or +1 — it returns some positive value, zero, or some negative value. The exact positive/negative value is implementation-defined, but in practice, most implementations return the difference of the first mismatched characters. That's why this program returns *a - *b rather than a normalized value — it matches strcmp's behaviour, and the sign is what matters for ordering. Callers should only rely on the sign (result < 0, result == 0, result > 0), not the exact magnitude.

The unsigned char casts are also important. Plain char can be signed on some platforms, which means characters with values above 127 (like accented letters in Latin-1) are negative. If you compare signed char values, the sign of the difference can be wrong for those characters. Casting to unsigned char makes the comparison well-defined across platforms and matches what strcmp does internally. It's a one-character change that prevents a class of subtle bugs.

Complete C Program

Program: compare two strings using a function and pointers

#include <stdio.h>

/* Compare two strings lexicographically, character by character.
   Returns 0 if equal, a positive value if s1 > s2, negative if s1 < s2. */
int str_compare(const char *s1, const char *s2) {
    const unsigned char *a = (const unsigned char *)s1;
    const unsigned char *b = (const unsigned char *)s2;

    while (*a != '\0' && *a == *b) {
        a++;
        b++;
    }
    return (int)(*a - *b);
}

int main(void) {
    const char *pairs[][2] = {
        {"apple",   "apple"},
        {"apple",   "apply"},
        {"apple",   "app"},
        {"app",     "apple"},
        {"banana",  "apple"},
        {"apple",   "Banana"},
        {"",        ""},
        {"abc",     ""},
        {"",        "abc"}
    };
    int n = (int)(sizeof(pairs) / sizeof(pairs[0]));

    printf("String comparison results:\n");
    printf("--------------------------\n");
    for (int i = 0; i < n; i++) {
        const char *s1 = pairs[i][0];
        const char *s2 = pairs[i][1];
        int r = str_compare(s1, s2);
        const char *rel = (r == 0) ? "==" : (r < 0 ? "<" : ">");
        printf("  \"%s\" %s \"%s\"   (returned %d)\n", s1, rel, s2, r);
    }

    /* Interactive comparison */
    char a[128], b[128];
    printf("\nEnter first string : ");
    if (scanf("%127s", a) != 1) return 0;
    printf("Enter second string: ");
    if (scanf("%127s", b) != 1) return 0;

    int r = str_compare(a, b);
    if (r == 0) {
        printf("\"%s\" is equal to \"%s\"\n", a, b);
    } else if (r < 0) {
        printf("\"%s\" is less than \"%s\"\n", a, b);
    } else {
        printf("\"%s\" is greater than \"%s\"\n", a, b);
    }

    return 0;
}
                                    

Program Output

String comparison results:
--------------------------
  "apple" == "apple"   (returned 0)
  "apple" < "apply"   (returned -14)
  "apple" > "app"     (returned 108)
  "app" < "apple"     (returned -108)
  "banana" > "apple"  (returned 1)
  "apple" > "Banana"  (returned 31)
  "" == ""             (returned 0)
  "abc" > ""          (returned 97)
  "" < "abc"          (returned -97)

Enter first string : hello
Enter second string: world
"hello" is less than "world"
                                

The output covers a range of cases: identical strings (return 0), mismatches in the middle (apple vs apply — differs at the last character, 'e' vs 'y', difference -14), prefix relationships (apple vs app — apple has more characters, so its null terminator compares against 'l', difference 108), case sensitivity (apple vs Banana — 'a' (97) vs 'B' (66), difference 31), and empty string edge cases. The interactive run compares hello and world and reports hello as less than world. Notice that the returned values are not normalized to ±1 — they're the raw character differences, exactly like strcmp.

Step-by-Step Explanation

Let's walk through the pointer mechanics and the comparison logic.

1. The function signature

int str_compare(const char *s1, const char *s2) takes two pointers to const char. The const is essential: the function only reads the strings, never modifies them, so callers can pass string literals (which are read-only) without warnings. This is exactly what strcmp does. The return type is int because the function reports the comparison result.

2. The unsigned char casts

const unsigned char *a = (const unsigned char *)s1; reinterprets the char * as an unsigned char *. This doesn't change what memory is pointed at — it changes how the bytes are interpreted when dereferenced. On platforms where char is signed (common), characters with byte values ≥ 128 (e.g., accented letters in Latin-1, or any non-ASCII byte in UTF-8) are negative char values. Comparing those as signed would give the wrong sign for the difference. Casting to unsigned char makes the comparison well-defined: the value is always in 0..255, so *a - *b is always the correct difference. Standard strcmp does this internally; so does this program.

3. The loop condition

while (*a != '\0' && *a == *b) has two parts, and both matter. *a != '\0' says "keep going only if s1 hasn't ended." If s1 ends, the loop stops regardless — and the values of *a and *b at that point determine the result. *a == *b says "keep going only if the characters match." If they differ, the mismatch is the decisive position and the loop stops. Combining them with && gives: "keep going while both strings have a character and those characters are equal."

4. Why we only check *a != '\0' and not *b != '\0'

It might seem like you need to check both strings for the null terminator. But the condition *a == *b already handles it. If *a is not '\0' and *a == *b, then *b is also not '\0' (because it equals *a). So *b can only be '\0' when *a is also '\0' — that is, when both strings have ended simultaneously. In every other case, *a being non-null ensures both strings have a character. This is a small but elegant simplification; it's also why the loop terminates correctly when one string is a prefix of the other.

5. Why return *a - *b instead of a normalized value

The return value is the difference of the first mismatched characters (or 0 if no mismatch, because both *a and *b are '\0' at that point). This matches strcmp's convention. The exact magnitude carries information — for "apple" vs "apply", the return is -14, because 'e' (101) minus 'y' (121) is -14. But callers shouldn't rely on the exact magnitude; they should use the sign. Returning the raw difference is simple, fast, and matches the standard, which is why it's the conventional choice.

6. Tracing "apple" vs "apple"

a and b advance through 'a', 'p', 'p', 'l', 'e' — all matching. On the next iteration, *a is '\0', so the loop stops (even though *a == *b is also true, since *b is '\0'). The return is '\0' - '\0' = 0, indicating equality. Both strings ended at the same position, so they're equal.

7. Tracing "apple" vs "apply"

The first four characters match: 'a', 'p', 'p', 'l'. On the fifth comparison, *a = 'e' and *b = 'y'. The loop condition *a == *b is false, so the loop exits. The return is 'e' - 'y' = 101 - 121 = -14. Negative means s1 < s2, which is correct — 'e' comes before 'y' in ASCII order.

8. Tracing "apple" vs "app"

The first three characters match: 'a', 'p', 'p'. On the fourth comparison, *a = 'l' (still inside "apple") and *b = '\0' (the end of "app"). The loop condition *a == *b is false (since 'l' ≠ '\0'), so the loop exits. The return is 'l' - '\0' = 108 - 0 = 108. Positive means s1 > s2, which is correct — a longer string that starts with the same characters is larger, because the shorter string's null terminator (0) is smaller than any real character.

9. Case sensitivity

The comparison is case-sensitive: 'a' (97) is not equal to 'A' (65). For "apple" vs "Banana", the first characters are 'a' and 'B'. 'a' - 'B' = 97 - 66 = 31, positive, so "apple" > "Banana". This may be surprising if you expect "apple" to come before "Banana" alphabetically — but ASCII puts uppercase letters before lowercase ones, so 'B' < 'a' and "Banana" < "apple" in ASCII order. This is one of the most common sources of confusion in string comparison, and it's a good reason to use a case-insensitive variant (strcasecmp, or a custom version using tolower) when the application needs case-insensitive ordering.

10. Empty string edge cases

Empty vs empty: both *a and *b are '\0', so the loop doesn't run, and the return is 0 - 0 = 0 — equal. Empty vs "abc": *a = '\0', so the loop doesn't run, and the return is 0 - 'a' = -97 — negative, so the empty string is smaller. "abc" vs empty: the loop doesn't run (because *b = '\0' makes *a != *b false for the first comparison, since *a = 'a' ≠ '\0'), and the return is 'a' - 0 = 97 — positive, so "abc" is larger. All three cases are handled correctly by the same loop, with no special-casing.

11. Why no explicit length comparison

A common beginner mistake is to first compare the lengths and then compare the characters. But length comparison alone doesn't work — "abc" and "abd" have the same length but are not equal. And comparing lengths first is unnecessary for strings that differ at a non-null character. The character-by-character walk handles both cases: it finds the first mismatch (whether that's a real character or a null terminator) and returns immediately. There's no need to know the lengths in advance.

12. Complexity

The loop runs at most min(len(s1), len(s2)) + 1 times — specifically, once per matching character, plus one final iteration where either the characters differ or one string ends. So time is O(min(len1, len2)) in the best case (equal strings) and O(1) in the best case for completely different first characters. Space is O(1) — two pointers, regardless of string length. This is optimal: you can't determine the relationship between two strings without examining characters until the first mismatch, and examining them takes at most min(len1, len2) steps.

🎯 Remember this: Compare strings = walk both with two pointers in lockstep; stop at the first mismatch or when s1 ends; return the difference of the characters at the stopping point. Return 0 for equal, positive for s1 > s2, negative for s1 < s2. Use unsigned char casts to handle high-bit characters safely.

Frequently Asked Questions

1. Why not just use strcmp from <string.h>?

You could — strcmp does exactly this. But the assignment asks you to implement the comparison yourself, and writing it teaches you how the standard library function works internally: the two-pointer walk, the early exit on mismatch, the character difference return convention, and the unsigned char casts. Understanding these details is important for debugging your own string code and for reasoning about edge cases (like embedded nulls or non-ASCII bytes). Once you've written it, you'll never be surprised by strcmp's behaviour again.

2. Why does the function return the character difference instead of just -1, 0, +1?

Because that's what strcmp does, and it's more informative: the magnitude of the return value tells you how different the first mismatched characters are. For example, "apple" vs "apply" returns -14 (because 'e' - 'y' = 101 - 121 = -14), and "apple" vs "Banana" returns 31 ('a' - 'B' = 97 - 66 = 31). Callers should only rely on the sign, but the exact value can be useful in diagnostics. Returning the raw difference is also simpler — one subtraction, no normalisation logic. Both are valid designs; matching strcmp makes it interoperable with existing string-handling code.

3. Why are the pointers cast to unsigned char *?

Because char can be signed on many platforms, and comparing signed characters gives the wrong sign for characters with byte values ≥ 128 (e.g., accented letters, non-ASCII bytes in UTF-8). Casting to unsigned char ensures that every character is in the range 0..255, so the subtraction *a - *b always gives the correct difference. This matters in production code that handles international text or binary data, and it's what standard strcmp does internally. For ASCII-only input, the cast has no effect — but it's still the right thing to do.

4. Why does the loop condition only check *a != '\0' and not both strings?

Because the condition *a == *b already ensures *b isn't '\0' before *a is. If *a != '\0' and *a == *b, then *b must also be non-null (it equals *a). So checking both would be redundant. The one condition that does need to be there is *a != '\0', because if s1 ends, we should stop — that's the loop's termination condition. Some implementations write the condition as while (*a && *a == *b), relying on the fact that '\0' is falsy, which is equivalent and more compact. Both forms are correct; the explicit '\0' is arguably clearer.

5. How do I make the comparison case-insensitive?

Use tolower (or toupper) on both characters before comparing: while (*a != '\0' && tolower(*a) == tolower(*b)) { a++; b++; }. Include <ctype.h>. The cast to unsigned char before tolower is important — tolower expects a value in the range of unsigned char (or EOF), and passing a negative char is undefined behaviour. So: tolower((unsigned char)*a). The rest of the function is unchanged. Note that case-insensitive comparison isn't part of the standard C library — there's no strcasecmp in ISO C (though POSIX provides one) — so implementing it yourself is a common extension.

6. What is the time and space complexity?

Time is O(min(len1, len2)) — the loop runs at most min(len1, len2) times to find the first mismatch, plus a constant. For equal strings, that's the full length of either; for strings that differ at the first character, it's O(1). Space is O(1) — two pointers and a couple of temporaries, regardless of string length. This is optimal: you can't determine the relationship between two strings without examining characters until the first mismatch, and examining them takes at most min(len1, len2) steps. No comparison-based algorithm can do better in the worst case.

💡 Tip: Once this works, try building related string functions using the same two-pointer pattern: str_length (walk one pointer to the terminator), str_copy (walk source and destination together), str_concat (walk to the end of the destination, then copy), and str_reverse (two pointers meeting in the middle). They all use the same idea — a pointer walks a string — with different comparison and advancement rules. Mastering one makes the others easy.

📖 Related Tutorials

  • 7. Compare Two Strings Using Pointers
  • 8. Copy One String to Another Using Pointers
  • 5. Length of a String Using Pointers
  • 6. Concatenate Two Strings Using Pointers
  • 21. Copy One String to Another Using a Function and Pointers
  • All 30 Pointer Assignments

Previous Topic: -->> 21. Copy One String to Another Using a Function and Pointers   ||   Next Topic: -->> 23. Length of a String Using a Function and Pointers


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.