Skip to content

Instantly share code, notes, and snippets.

@RickBarretto
Created July 31, 2023 22:49
Show Gist options
  • Save RickBarretto/ed0065c1a2144deb4b3250ce125956b0 to your computer and use it in GitHub Desktop.
Save RickBarretto/ed0065c1a2144deb4b3250ce125956b0 to your computer and use it in GitHub Desktop.
Kwargs (keyword arguments) in C programming language. (Positional and optional arguments)
#include <stdio.h>
/** KW(fn): Just a macro that expands to fn_kwargs
* - fn: the function's name
*/
#define KW(fn) struct fn ## _kwargs
/** def_kwargs(fn, definition)
* - fn: the function's name
* - definition: a block with internal definition of arguments
*
* Usage:
* def_kwargs(function, { int arg1; double arg2 });
*
* Expansion:
* struct function_kwargs { int arg1; double arg2 };
*/
#define def_kwargs(fn, definition) KW(fn) definition;
/** ** Implementation ** **/
/** struct print_user_kwargs
* - char [65]name;
* - char [65]repository;
* - int commits;
*/
def_kwargs(print_user, { char name[65]; char repository[65]; int commits; });
/** print_user(unsigned id, **kwargs): Prints the user's information
* - id: it's the user's id
* - kwargs:
* obligatory:
* - int commits: the amount of commits in that repo
* optionals:
* - char [65]name = "Anonymous": the user's name
* - char [65]repository = "Private": the user's repo
*/
#define print_user(id, ...) \
internal_print_user((id), (KW(print_user)){ \
.name = "Anonymous", .repository = "Private", \
__VA_ARGS__ })
static void internal_print_user(unsigned int id, KW(print_user) kwargs)
{
// don't forget to #include <stdio.h>
printf("ID: %d\n", id);
printf(" user: %s\n", kwargs.name);
printf(" repository: %s\n", kwargs.repository);
printf(" commits: %d\n", kwargs.commits);
return;
}
int main(void)
{
print_user(10, .name = "RickBarretto", .repository = "proto.c", .commits = 15);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment