Why use const char* instead of string?

I see it all over the place. Personally, I prefer strings.

I prefer them too, but they are not compatible with other languages or most win32 api functions. If you are not concerned with either of those then by all means use std::string.

Edited 5 Years Ago by Ancient Dragon: n/a

The main reason for using const char* is because it is compatible and linkable with C. Many APIs and other libraries have C interfaces (you use the API via a collection of C-like functions). With these functions, you have no choice but to use types that exist in C, which includes primitive types like int, float, char, double, short, etc. and any pointer type (including C++ class pointers, since they are just normal pointers). In other words, you can't use pass-by-value of any class type (including std::string), and you can't use any pass-by-reference of any type.

The reason why C interfaces are used is mainly because C is so simple that it does not need to mangle function names to account for parameter types (which C++ has to do to achieve function overloading), and because types in C have a trivial byte alignment because it doesn't have to deal with virtual tables and multiple inheritance like C++ does. So, C interfaces are preferred for portability and binary compatibility, and along with that comes the burden of having to convert strings to const char* and vice versa (or sometimes write code that uses const char*, just to avoid converting back-and-forth all the time).

In internal code (code that doesn't use an API directly, or code that isn't at the interface of an API), if programmed in C++, I see absolutely no reason to use const char* instead of std::string. The only people using char* in these situations are those who suffer from the "C-hacker syndrome".

This article has been dead for over six months. Start a new discussion instead.