4 ms·
String constant generation for C is wrong. It should be const char X[] = "This string cannot be reassigned."; instead of const char *X = "This string CAN
by tempodox 6y ago
String constant generation for C is wrong. It should be
const char X[] = "This string cannot be reassigned.";
instead of
const char *X = "This string CAN be reassigned";
In the second case, you can do
X = "Another value";
X wouldn't be constant, but only the value it points to. Also, it costs sizeof(char *) more memory than the actual string contents.
- nyellin 6y agoHmm, I'm torn on this. Using `const char* const` can solve the first issue. Regarding the memory, `const char X[]` is obviously better but it is a little less familiar to most developers. I'm not sure if it is worth saving the bytes as the cost of clarity.
- cjaybo 6y agoIt's surprising to me that you think char arrays might be unfamiliar to C developers!
- nyellin 6y agoI should have been more clear. It's not that developers are unfamiliar with the string/array equivalence in C, but rather it's less common to encode constant strings that way and I've rarely seen it done. I can find data showing that adding the second const is uncommon. Here are the number of code results for different github searches: "const char " - 310 million results "const char" - 385 million results "const char * const" - 30 million results "const char* const" - 37 million results "const char *const" - 36 million results Unfortunately I'm not sure how to search for the array style syntax. One way or another, my point is that I'm more interested in optimizing for readablity and the way people expect things to be defined rather than the extra bytes.
- s_gourichon 6y agoThe better syntax being uncommon is not a reason to not adopt it. Sometimes the wide majority can be unaware of the better choice. I would rather see the change suggested as an opportunity to educate the developers.
- UncleMeat 6y agoI don't know about C, but in C++ this is also not safe in a header file.
- tempodox 6y agoTrue. Putting that in a header file will lead to linker errors if the file is included more than once.