Coffee Maker Coffee Maker - 1 year ago 108
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
modifier? If so, why?

Answer Source

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";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download