There are some good answers already, but no one's implemented a const char* array[]
. As David C. Rankin said in his comment:
Create a global array of pointers to string literals holding the days, e.g. const char *days[] = { "Monday", "Tuesday", ... }, then just return days[x];
I'm surprised this wasn't the "go to" implementation, and I'm curious to hear why from everyone who disagrees. In the mean time, this is what this implementation looks like:
const char* daysOfTheWeek[] = {
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
};
Implementing a function to return the specified day of the week is then trivial:
void PrintDayOfTheWeek(int n) {
if ((n < 0) || (n > 6)) {
// TODO: Handle error here somehow
// Currently ignores call with invalid parameter
return;
}
printf("Day %d: %s\n", n+1, daysOfTheWeek[n]);
}
To test this, you can iterate through a simple for
loop from 0 to 6.
int main()
{
for (int i = 0; i < 7; ++i) {
PrintDayOfTheWeek(i);
}
return EXIT_SUCCESS;
}
Output:
Day 1: Monday
Day 2: Tuesday
Day 3: Wednesday
Day 4: Thursday
Day 5: Friday
Day 6: Saturday
Day 7: Sunday
Now, in your question, you specifically asked for a function that takes in an enum
[value] and returns a string pointer. Implementing this is pretty similar to the previous example. We begin by declaring the enum DAYS
:
typedef enum DAYS {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
} Day;
Conveniently, enums
assign a value of zero (0
) for their first value unless otherwise assigned, so this enum
already works as expected with our PrintDayOfTheWeek(int n)
function.
So, for example, rather than calling it with an number directly, we can now define a new function that takes in the day we want and returns the string, as you requested. So just pass in on of the names of the week defined in the enum DAYS
:
const char* dayOfTheWeek(Day day) {
return daysOfTheWeek[day];
}
And we can print it like this:
printf("%s\n", dayOfTheWeek(SUNDAY));
Output:
Sunday
Here's something cool, too. Enums are best used in a switch statement, obviously, it is technically possible to iterate over an enum, like this:
for (Day day = MONDAY; day <= SUNDAY; ++day) {
PrintDayOfTheWeek(day);
}
While enums
are obviously not meant to be iterated over, I think that example is pretty cool because I think it helps remember that enums are just integral data types. They also give no additional type safety, which is why enum classes were added in to C++.