LearnFrenzy
Sign in Take a free test

C Const · const Programs · Question 5

Default settings in a const struct, overridden in a copy Solution, output & explanation

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

Keep default settings in a static const struct and build user settings by copying and overriding them.

Solution
main.c
#include <stdbool.h>
#include <stdio.h>

struct settings {
    int font_size;
    bool dark_mode;
    const char *language;
};

static const struct settings DEFAULTS = {.font_size = 14, .dark_mode = false, .language = "en"};

void show(const char *who, const struct settings *s) {
    printf("%-8s font %d, %s, %s\n", who, s->font_size, s->dark_mode ? "dark" : "light", s->language);
}

int main(void) {
    struct settings mine = DEFAULTS;      /* start from the defaults */
    mine.dark_mode = true;                /* override what the user changed */
    mine.language = "hi";
    show("defaults", &DEFAULTS);
    show("user", &mine);
    return 0;
}

Output Verified by compiling and running

defaults font 14, light, en
user     font 14, dark, hi

The defaults can never be changed by accident, and struct assignment makes a full copy to customise. show() takes const struct settings *, so it accepts both.

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