LearnFrenzy
Sign in Take a free test

C Const · const Programs · Question 2

Month name from a number with a const pointer array in C Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

Return the full month name for 1–12 and "invalid" otherwise, using read-only data.

Solution
main.c
#include <stdio.h>

const char *month(int m) {
    static const char *const names[] = {"January", "February", "March", "April", "May", "June",
                                        "July", "August", "September", "October", "November", "December"};
    if (m < 1 || m > 12)
        return "invalid";
    return names[m - 1];
}

int main(void) {
    int tests[] = {1, 8, 12, 0};
    for (int i = 0; i < 4; i++)
        printf("%d: %s\n", tests[i], month(tests[i]));
    return 0;
}

Output Verified by compiling and running

1: January
8: August
12: December
0: invalid

The range check guards the table index. Returning const char * stops callers from writing into the shared strings.

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