Skip to content

Instantly share code, notes, and snippets.

@jmatth11
Created August 14, 2025 17:39
Show Gist options
  • Select an option

  • Save jmatth11/5a0e123960b70ac1d5fcda2c006ec2b3 to your computer and use it in GitHub Desktop.

Select an option

Save jmatth11/5a0e123960b70ac1d5fcda2c006ec2b3 to your computer and use it in GitHub Desktop.
named parameters in C
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char *name;
size_t len;
int value;
} option_t;
void display_cmd_fn(option_t opt);
// macro to set defaults and allow for overwrites
#define display_cmd(...) \
display_cmd_fn((option_t){ .name = "default", .len = 7, __VA_ARGS__ })
void display_cmd_fn(option_t opt) {
if (opt.name != NULL) {
printf("name = %s\n", opt.name);
} else {
printf("name = NULL\n");
}
printf("len = %lu\n", opt.len);
printf("value = %d\n", opt.value);
}
int main (void) {
// using default values.
display_cmd(.value = 10);
// overwriting values.
display_cmd(.name = "scale", .len = 5, .value = 42);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment