Skip to content

Instantly share code, notes, and snippets.

@atextor
Created August 31, 2017 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atextor/43e4f6313afba84ad6e656c5abba0755 to your computer and use it in GitHub Desktop.
Save atextor/43e4f6313afba84ad6e656c5abba0755 to your computer and use it in GitHub Desktop.
#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