Created
August 31, 2017 19:54
-
-
Save atextor/43e4f6313afba84ad6e656c5abba0755 to your computer and use it in GitHub Desktop.
This file contains 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 <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