Declare an enum with explicit values for some HTTP status codes and print a message for each, including an unknown code.
Solution
main.c
#include <stdio.h>
enum status { OK = 200, CREATED = 201, NOT_FOUND = 404, SERVER_ERROR = 500 };
const char *text(enum status s) {
switch (s) {
case OK: return "OK";
case CREATED: return "Created";
case NOT_FOUND: return "Not Found";
case SERVER_ERROR: return "Internal Server Error";
}
return "Unknown"; /* any other int value */
}
int main(void) {
enum status list[] = {OK, NOT_FOUND, 418};
for (int i = 0; i < 3; i++)
printf("%d %s\n", list[i], text(list[i]));
return 0;
}
Output Verified by compiling and running
200 OK
404 Not Found
418 Unknown
Enum constants can have any int values. An enum variable can still hold other values (here 418), so the function needs a fallback after the switch.
More Declarations and Initializations practice questions
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!