Coffee Maker Coffee Maker - 4 months ago 16
C Question

Is it bad to declare a C-style string without const? If so, why?

Doing this in C++

char* cool = "cool";


compiles fine, but gives me a warning: "deprecated conversion from string constant to char*".

I would never willfully use a C-style string over std::string, but just in case I'm asked this question: is it bad practice to declare a C-style string without the
const
modifier? If so, why?

Answer

Yes, this declaration is bad practice, because it allows many ways of accidentally provoking Undefined Behavior by writing to a string literal, including:

cool[0] = 'k';
strcpy(cool, "oops");

On the other hand, this is perfectly fine, since it allocates a non-const array of chars:

char cool[] = "cool";