Skip to content

Instantly share code, notes, and snippets.

@mkmik
Created October 16, 2014 17:53
Show Gist options
  • Save mkmik/cab00a25be991f2d3166 to your computer and use it in GitHub Desktop.
Save mkmik/cab00a25be991f2d3166 to your computer and use it in GitHub Desktop.
/*
* Quicky and dirty optional arguments. Requires (ANSI) C99.
*
* Good:
* 1. Allows to convert any existing function to a optarg function.
* 2. Typed parameters.
*
* So so:
* 3. Simple defaults are possible but might result in compiler
* warnings that can be suppressed but ...
*
* Bad:
* 4. Requires (ANSI) C99.
* 5. Doesn't support repeated parameters (like Amiga tags),
* but it's easy to have helpers generate structures with
* repeated content
*
*/
#include <stdio.h>
typedef struct {
int deadline;
int n_headers;
} ns_send_opts_t;
// if compiled with -Wno-initializer-overrides, we can cleanly implement default values here
// #define ns_send(addr, body,...) ns_send_o(addr, body, (ns_send_opts_t){ .deadline=1, __VA_ARGS__})
#define ns_send(addr, body,...) ns_send_o(addr, body, (ns_send_opts_t){__VA_ARGS__})
void ns_send_o(char* addr, char* body, ns_send_opts_t opts) {
printf("sending %s to %s, deadline: %d, headers: %d\n", addr, body, opts.deadline, opts.n_headers);
}
int main() {
ns_send("foo", "bar", .deadline=360);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment