const string vs. #define

Prefer the second option. If you use the first option (preprocessor), you are limiting your flexibility with the object.

Consider the following... You won't be able to compare strings this way:

if (str1 == "some string")
{
    // ...
}

If it's C++, you should use the C++ Standard Library's std::string. It's much more clear than a preprocessor macro, it will have a single location in memory when it's defined, and it has all the extra functionality of std::string instead of only pointer comparisons as is the case with the implicit const char* that are created with a preprocessor macro.


If it is C++ instead of C, you should really use some variable instead of a preprocessor macro. The former is clearer than the latter. Furthermore, if you use C++17, you can use inline variables:

inline const std::string str = "foobar";

or

// constexpr is implicitly inline
constexpr char str0[] = "foobar";
constexpr const char* str1 = "foobar";
constexpr std::string_view str2 = "foobar";

This is also clearer than using extern and can be used in header-only APIs as well.

Tags:

C++