basics · intermediate · ~15 min

Designated Initializer Configuration

Use designated initializers to construct clean default configs with validated override semantics.

Challenge

C99 designated initializers (.field = value) enable self-documenting, resilient structure initialization where unspecified fields are guaranteed to be zeroed by the compiler.

Your Task

Given the server configuration struct:

typedef struct {
    int port;
    int max_clients;
    int keepalive_seconds;
    int enable_tls;
    int debug_logging;
} ServerConfig;

Implement:

ServerConfig create_default_config(void);
int apply_config_override(ServerConfig *cfg, const char *key, int value);

Rules

  1. create_default_config: return a ServerConfig initialized with:
    • port: 8080
    • max_clients: 128
    • keepalive_seconds: 60
    • enable_tls: 0
    • debug_logging: 0
  2. apply_config_override:
    • If cfg == NULL or key == NULL, return -1.
    • If key is "port": must be in range [1, 65535]. Set cfg->port = value and return 0. If invalid, return -1.
    • If key is "max_clients": must be in range [1, 10000]. Set cfg->max_clients = value and return 0. If invalid, return -1.
    • If key is "enable_tls": must be 0 or 1. Set cfg->enable_tls = value and return 0. If invalid, return -1.
    • Any other key: return -1.

Example

ServerConfig cfg = create_default_config(); // port 8080
apply_config_override(&cfg, "port", 443); // returns 0, cfg.port == 443
apply_config_override(&cfg, "port", 99999); // returns -1, cfg.port remains 443

Input format

cfg: pointer to ServerConfig; key: string setting name; value: integer parameter.

Output format

Returns default ServerConfig struct or status code 0/-1.

Constraints

Zero dynamic allocations. Bounded parameter validation.

Starter code

#include <stddef.h>

typedef struct {
    int port;
    int max_clients;
    int keepalive_seconds;
    int enable_tls;
    int debug_logging;
} ServerConfig;

ServerConfig create_default_config(void) {
    ServerConfig c = {0};
    return c;
}

int apply_config_override(ServerConfig *cfg, const char *key, int value) {
    (void)cfg; (void)key; (void)value;
    return -1;
}

Common mistakes

Modifying config before validating range; uninitialized struct fields.

Edge cases to handle

Invalid port numbers (< 1 or > 65535) rejected; NULL pointers return -1.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.