I have a simple function that takes a char and return a string, in C it looks like;
char* get_string(char c) {
switch(c) {
case 'A': return "some string";
Case 'B': return "some other string";
...
And it works fine, but then I wanted my code to work in C++, and the C++ compilers throws a gazillions “deprecated conversion from string constant to ‘char*’”. I understand the warning, but I’m not 100% sure what is the best way to implement the function so it will work, fast, on both C and C++. This function is being called a lot, it’s an important bottleneck, so it has to be fast. My best try is;
char* get_string(char c) {
char* str = (char*)malloc(50);
switch(c) {
case 'A':
sprintf(str, "some string");
return str;
Case 'B':
sprintf(str, "some other string");
return str;
...
Return a
const char*instead ofchar*. Theconstin this context means “this pointer points to a constant pointee” – in other words, the caller cannot modify the returned string. This allows the compiler to place the strings in some memory location so theget_string()function can just return addresses to those strings. If the caller needs to modify the returned string, they can allocate their own buffer and copy it (preferably viastd::string).