Created
August 14, 2025 17:39
-
-
Save jmatth11/5a0e123960b70ac1d5fcda2c006ec2b3 to your computer and use it in GitHub Desktop.
named parameters in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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