All,
Please excuse my potentially noob-ish question. I haven't touched strings in C (or C in general) in a while, and I seem to recall there being different ways you can return a C string from a function (as discussed here: https://stackoverflow.com/questions/25798977/returning-string-from-c-functionhere).
I am currently implementing a weird driver API that I inherited. Long story short, I get passed in a "device index", and then return the device name that will be used to open() the device.
Here is my implementation:
static const char* getDeviceName(uint8_t device_index) {
static const char* const device_names[] =
{"", "/dev/some_device", "/dev/some_other_device", "", "", "", "", "", ""};
if (device_index > 8) {
return "";
} else {
return device_names[device_index];
}
}
Long story short, I am provided an index (as a uint8_t for some reason) and then need to convert it to a string. As such, I create a constant array of constant strings, which is static. Note that many of these indexes are empty since they currently do not map to a device, but may in the future.
If the device index is out of bounds, I return the empty string. If the index is in bounds, I index into my constant array and return that value.
Since my C is rusty, I'm wondering if any of the above is UB, or if there are better ways of doing this. I know I can have the function return void and have the caller pass in a char* for me to populate, but I think the above is the cleanest way, since I can do things like "open(getDeviceName(index));".
In addition to my questions about UB, I also wanted to make sure that the code is const correct.
At any rate, let me know your thoughts. Thanks in advance for the help.