LearnFrenzy
Sign in Take a free test

Declarations and Initializations · Declaration Programs · Question 4

Default settings and an update with a compound literal in C Solution, output & explanation

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

Keep default settings in a const struct, then replace a copy with new values using a compound literal.

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

struct settings {
    int volume;
    bool muted;
    const char *theme;
};

static const struct settings defaults = {.volume = 50, .theme = "light"};

int main(void) {
    struct settings s = defaults;
    s = (struct settings){.volume = 80, .muted = s.muted, .theme = "dark"};
    printf("%d %d %s | %d %d %s\n", defaults.volume, defaults.muted, defaults.theme, s.volume, s.muted, s.theme);
    return 0;
}

Output Verified by compiling and running

50 0 light | 80 0 dark

The defaults never change. A compound literal builds a complete new struct in one expression – any member not named in it would be zero, so values to keep (muted) are copied explicitly.

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