software-development

How to Check if Two Strings Are Equal in C

In C, string literals are represented as arrays of characters, and when you declare a string literal such as "hello" , it evaluates to the address of the first element of that a...

Mara Ellison
How to Check if Two Strings Are Equal in C

Why == Does Not Work for String Equality in C

In C, string literals are represented as arrays of characters, and when you declare a string literal such as "hello", it evaluates to the address of the first element of that array. The expression == compares these addresses, not the actual sequence of characters. Therefore, two distinct string literals with the same content may reside at different memory locations, causing == to yield false even when the text appears identical. To determine whether two strings contain the same characters, you must compare their contents byte by byte using the standard library function strcmp from <string.h>.

Using strcmp for Content Comparison

Convention and Return Values

The function strcmp is declared in string.h and follows a consistent contract: it compares two strings lexicographically based on the numeric values of their characters. It returns an integer with these meanings:

  • Zero indicates the strings are identical in content.
  • A negative value indicates the first differing character in the first string is less than the corresponding character in the second string.
  • A positive value indicates the first differing character in the first string is greater than the corresponding character in the second string.

Because the exact non-zero value is implementation-defined, you should only test whether the result is zero for equality. The canonical pattern is strcmp(s1, s2) == 0 to check if s1 and s2 are equal in content.

Correct and Incorrect Usage Patterns

Common Pitfalls

Developers new to C often mistakenly write if (s1 == s2) expecting it to compare text. This pattern can appear to work in limited scenarios, such as when the compiler interns identical string literals or when both pointers reference the same literal due to compiler optimizations. However, relying on this behavior is unsafe and non-portable. Pointer comparison provides no guarantee about string content and may break with different compilers, optimization settings, or when strings are constructed at runtime.

Examples of Proper Comparison

To compare two strings safely, assign their literals or buffers to char pointers or arrays, then use strcmp. Remember to include string.h before using the function. Here are minimal, correct examples:

#include <stdio.h>
#include <string.h>

int main(void) {
    const char *a = "test";
    const char *b = "test";
    if (strcmp(a, b) == 0) {
        printf("Strings are equal\n");
    } else {
        printf("Strings are not equal\n");
    }
    return 0;
}

When working with character arrays rather than pointers, the same approach applies because arrays decay to pointers when passed to functions. For runtime-constructed strings, ensure they are null-terminated, as strcmp relies on the null terminator to detect the end of each string. Omitting the null terminator leads to undefined behavior, including reading past allocated memory.

Edge Cases and Safety Considerations

Null Pointers and Empty Strings

Passing a null pointer to strcmp results in undefined behavior; therefore, you must ensure both strings are valid before calling it. If your program can produce null pointers, perform an explicit check or initialize pointers to NULL and validate them. An empty string is represented by two consecutive null characters, "", and strcmp handles empty strings correctly, returning zero when both inputs are empty. Treat null pointers as distinct from empty strings, as their semantics differ in C.

AttributeVerified DetailSource Type
Comparison MethodUse strcmp(s1, s2) == 0 for content equalityC Standard <string.h>
== OperatorCompares pointer addresses, not string contentC Language Specification
Return Value EqualityOnly the result zero guarantees strings are equal in contentPOSIX/SUS specification for strcmp
Null Pointer BehaviorPassing null to strcmp is undefined behaviorC Standard rationale and common libc implementations
Empty StringsTwo empty strings are considered equal by strcmpC Standard conformance

Performance and Memory Implications

strcmp operates in linear time relative to the length of the differing characters or the full length of the strings when they are equal. It compares bytes sequentially and stops at the first mismatch or at the terminating null character. This behavior generally makes it efficient for most practical uses, but in performance-critical loops over very long strings, the cost can become noticeable. No standard-library function avoids reading characters up to the mismatch point, as any correct string comparison must inspect bytes until a difference or terminator is found. For constant strings known at compile time, compilers can sometimes optimize repeated comparisons, but runtime strings require a full comparison each time.

International and Extended Character Considerations

strcmp compares the numeric values of unsigned char representations byte by byte using the machine's native character encoding, typically ASCII or a superset such as UTF-8. In ASCII-based encodings, this works predictably for basic Latin letters and digits, but it is not inherently aware of locale-specific collation rules or multibyte encodings beyond single-byte interpretations. For programs that require locale-aware ordering or support for wide characters, alternatives such as strcoll or wide-character functions may be more appropriate, though they introduce additional complexity and localization dependencies. If your application must handle UTF-8 text with correct linguistic ordering, you will need libraries that understand Unicode collation rather than relying on strcmp.

Summary and Best Practices

To check if two strings are equal in C, use strcmp from string.h and test whether its return value is zero. Avoid using == to compare string contents, as it only compares pointer addresses. Always ensure strings are null-terminated and that pointers are valid before calling strcmp. Be mindful that strcmp performs binary comparison of character values, which is suitable for basic ASCII and UTF-8 equality checks without locale-specific ordering. Following these practices helps you write correct, portable, and maintainable C code when comparing strings.

Related Reading

More pages in this topic cluster.

How to Make Minecraft Plugins: A Verified Technical Guide

Making a Minecraft plugin means writing server side code that hooks into the Minecraft server software to change or extend gameplay, commands, data, and integrations. Unlike mod...

Read next
Sprint Dirt: What It Is, Why It Happens, and How to Manage It

Sprint dirt is the accumulation of small, often invisible issues that slow teams down across a sprint—unclear requirements, brittle tests, flaky environments, and handoff fric...

Read next
Understanding Chandler Garbage Collection in Computing

In computing, garbage collection is an automatic memory management mechanism that reclaims unused objects to free resources. In the context of the Chandler information manager,...

Read next