LearnFrenzy
Sign in Take a free test

C Const · Predict the Output · Question 10

A function returning the same const string twice Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

What is the output of the following C program?

main.c
#include <stdio.h>

const char *level_name(int level) {
    static const char *const names[] = {"low", "medium", "high"};
    return names[level];
}

int main(void) {
    const char *a = level_name(1);
    const char *b = level_name(1);
    printf("%d %s\n", a == b, a);
    return 0;
}
  • A 1 medium Correct
  • B 0 medium
  • C 1 low
  • D 0 high
Correct Answer: Option A

The function returns a pointer to the same static string each time, so the two pointers are equal. Returning const char * tells callers they must not modify it.

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