Originally Posted by
Elysia
That only works if days is a global variable; otherwise you're returning the address of a local variable, assuming that a function is returning that information.
In which case, it would be more efficient to make the function take a buffer and size, do a switch and copy the appropriate string into the buffer.
Well it would be fine if this was the C++ forum, because the return type would then probably be std::string. However being C there's still nothing stopping us from doing it the preferred way, using a lookup table.
Code:
// Preconditions:
// inDayIndex is between 1 and 7
// outDayName points to a buffer big enough to hold at least 10 characters
void getDayOfWeekName(int inDayIndex, char *outDayName)
{
static const char days[7][] =
{ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
strcpy(outDayName, days[inDayIndex - 1]);
}
Don't use a switch where an explicit lookup table will work.
A switch is not more efficient. It is at best just as efficient, provided it happens to optimise down to a jump table. You're better off implementing it directly as a table on your own.