basics · intermediate · ~15 min
Use designated initializers to construct clean default configs with validated override semantics.
C99 designated initializers (.field = value) enable self-documenting, resilient structure initialization where unspecified fields are guaranteed to be zeroed by the compiler.
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);
create_default_config: return a ServerConfig initialized with:port: 8080max_clients: 128keepalive_seconds: 60enable_tls: 0debug_logging: 0apply_config_override:cfg == NULL or key == NULL, return -1.key is "port": must be in range [1, 65535]. Set cfg->port = value and return 0. If invalid, return -1.key is "max_clients": must be in range [1, 10000]. Set cfg->max_clients = value and return 0. If invalid, return -1.key is "enable_tls": must be 0 or 1. Set cfg->enable_tls = value and return 0. If invalid, return -1.-1.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
cfg: pointer to ServerConfig; key: string setting name; value: integer parameter.
Returns default ServerConfig struct or status code 0/-1.
Zero dynamic allocations. Bounded parameter validation.
#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;
}
Modifying config before validating range; uninitialized struct fields.
Invalid port numbers (< 1 or > 65535) rejected; NULL pointers return -1.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.