LearnFrenzy
Sign in Take a free test

Declarations and Initializations · Declaration Programs · Question 5

HTTP status codes as an enum with explicit values in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links