C++ std::strcmp: Common Pitfalls and Modern Alternatives

2025-08-26

std::strcmp is a function from the <cstring> header. Its purpose is to compare two C-style strings (null-terminated character arrays). It's important to remember that it's designed for C-style strings, not std::string objects. . It works by comparing the strings character by character until a difference is found or the end of a string is reached.

The function returns an integer value

A negative value if the first string comes before the second one lexicographically.

0 if the two strings are identical.

A positive value if the first string comes after the second one lexicographically.

Here's a quick example

#include <iostream>
#include <cstring>

int main() {
    const char* str1 = "apple";
    const char* str2 = "banana";
    const char* str3 = "apple";

    int result1 = std::strcmp(str1, str2); // str1 is less than str2, returns negative
    int result2 = std::strcmp(str1, str3); // str1 and str3 are equal, returns 0

    std::cout << "Comparison of 'apple' and 'banana': " << result1 << std::endl;
    std::cout << "Comparison of 'apple' and 'apple': " << result2 << std::endl;

    return 0;
}

This is the most common mistake. std::strcmp can't directly compare two std::string objects. If you try, you'll get a compile-time error.

Why it's a problem
std::string is an object, not a simple C-style array of characters. std::strcmp expects a pointer to a C-style string (const char*).

Solution
Use the built-in comparison operators (==, !=, <, >) for std::string. These are much more intuitive and safer.

Example of the wrong way (don't do this!)

#include <iostream>
#include <string>
#include <cstring>

int main() {
    std::string s1 = "hello";
    std::string s2 = "world";

    // This will cause a compile error!
    // int result = std::strcmp(s1, s2);

    return 0;
}

Correct way (the modern C++ approach)

#include <iostream>
#include <string>

int main() {
    std::string s1 = "hello";
    std::string s2 = "world";

    if (s1 == s2) {
        std::cout << "The strings are equal." << std::endl;
    } else if (s1 < s2) {
        std::cout << "s1 comes before s2." << std::endl;
    } else {
        std::cout << "s1 comes after s2." << std::endl;
    }

    return 0;
}

Passing a null pointer to std::strcmp results in undefined behavior, which can lead to crashes or unpredictable results. The function assumes it's receiving a valid C-style string.

Why it's a problem
std::strcmp will try to dereference a null pointer, causing a segmentation fault.

Solution
Always check if the pointers are not null before calling std::strcmp.

Example of the wrong way (dangerous!)

#include <iostream>
#include <cstring>

int main() {
    const char* str1 = "test";
    const char* str_null = nullptr;

    // This will likely crash your program!
    // int result = std::strcmp(str1, str_null);

    return 0;
}

Correct way (safe)

#include <iostream>
#include <cstring>

int main() {
    const char* str1 = "test";
    const char* str_null = nullptr;

    if (str1 && str_null) {
        int result = std::strcmp(str1, str_null);
        std::cout << "Result: " << result << std::endl;
    } else {
        std::cout << "One or both strings are null." << std::endl;
    }

    return 0;
}

In modern C++, you'll almost always want to use std::string instead of C-style strings. Here's why and how to do it.

This is the preferred method for comparing strings in C++. It's type-safe, handles memory management, and is far more readable.

Example

#include <iostream>
#include <string>

int main() {
    std::string s1 = "code";
    std::string s2 = "code";
    std::string s3 = "test";

    // Equality
    if (s1 == s2) {
        std::cout << "s1 and s2 are the same." << std::endl;
    }

    // Inequality
    if (s1 != s3) {
        std::cout << "s1 and s3 are different." << std::endl;
    }

    // Lexicographical comparison
    if (s1 < s3) {
        std::cout << "s1 comes before s3." << std::endl;
    }

    return 0;
}

The std::string::compare method is a member function of std::string that provides similar functionality to std::strcmp. It's particularly useful when you need to compare a substring or a std::string with a C-style string.

Example

#include <iostream>
#include <string>

int main() {
    std::string s1 = "hello";
    std::string s2 = "world";

    int result_str_compare = s1.compare(s2);

    if (result_str_compare < 0) {
        std::cout << "s1 comes before s2." << std::endl;
    } else if (result_str_compare == 0) {
        std::cout << "s1 and s2 are equal." << std::endl;
    } else {
        std::cout << "s1 comes after s2." << std::endl;
    }

    return 0;
}

cpp



Mastering C++ Unordered Set: A Guide to Buckets and Hashing

First, think of an std::unordered_set as a collection of items where the order doesn't matter, and each item is unique. It's built on a hash table


Troubleshooting student_t_distribution::n in C++

Hey there! Let's talk about the n parameter of the std::student_t_distribution in C++. This parameter is crucial because it represents the degrees of freedom


Common Mistakes with std::discard_block_engine::min()

The std::discard_block_engine is a pseudo-random number generator provided in the <random> header in C++. It's a type of random number engine adaptor that takes an underlying engine (like std::mt19937) and discards a certain number of its generated values



Mastering C++ PMR: select_on_container_copy_construction Explained

The most common issues arise from misunderstanding its purpose. It's not a generic allocator behavior; it’s specifically for PMR allocators


A Guide to std::nested_exception::nested_ptr: C++ Error Handling Best Practices

Think of std::nested_exception as a special wrapper for exceptions. It allows you to catch one exception and then "nest" it inside a new one


C++ Metaprogramming: Comparing Ratios at Compile Time

First off, std::ratio_not_equal is a compile-time type trait used for comparing two std::ratio types. It's defined in the <ratio> header


Demystifying C++ std::mutex: Avoiding Deadlocks and Lock Leaks

At its core, std::mutex is like a lock for your code. When you have multiple threads (think of them as different workers) trying to access the same piece of data at the same time


How to Properly Swap Elements When Using C++'s std::views::adjacent

The short answer is that you generally cannot use std::ranges::iter_swap directly on iterators from std::ranges::adjacent_view to modify the underlying container elements


The No-Op operator++: A Guide to std::front_insert_iterator in C++

First, let's understand what this operator is for. The std::front_insert_iterator is a special kind of iterator that, when you dereference it and assign a value (e.g., *it = x), it inserts that value at the front of the container


The Legacy of C++ do_encoding: Common Troubles and Robust Alternatives to std::codecvt

Since std::codecvt (and its associated virtual function do_encoding) is an internal part of the C++ localization system and has been largely replaced by better alternatives