Skip to content

Instantly share code, notes, and snippets.

@atextor atextor/named_args.c
Created Aug 31, 2017

Embed
What would you like to do?
#include <stdio.h>
#include <stdbool.h>
struct _named_t {
int arg1;
int arg2;
bool subtract_one;
};
int _calculate_sum(struct _named_t *args) {
int result = args->arg1 + args->arg2;
return args->subtract_one ? result - 1 : result;
}
#define calculate_sum(...) _calculate_sum(&(struct _named_t){ __VA_ARGS__ })
int main() {
int result;
// No surprise here
result = calculate_sum( 3, 4 );
printf( "%d\n", result ); // prints 7
// We can explicitly name arguments
result = calculate_sum( .arg1 = 3, .arg2 = 4 );
printf( "%d\n", result ); // prints 7
// When we name arguments, we can also give them in
// an arbitrary order
result = calculate_sum( .arg2 = 4, .arg1 = 3 );
printf( "%d\n", result ); // prints 7
// Also, we can add optional named arguments
result = calculate_sum( 3, 4, .subtract_one = true );
printf( "%d\n", result ); // prints 6
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.