Skip to content

Instantly share code, notes, and snippets.

@rahulrajaram
Created May 8, 2019 07:01
Show Gist options
  • Save rahulrajaram/9f6d98a225ad8a0c7bdc76417a234059 to your computer and use it in GitHub Desktop.
Save rahulrajaram/9f6d98a225ad8a0c7bdc76417a234059 to your computer and use it in GitHub Desktop.
Generic in C using macros
#include <string.h>
#include <stdio.h>
/*
* Macro function that initializes a struct object
* and returns it.
*
* For this to work, a `{type}Init` function must
* be defined.
*/
#define STRUCT_INIT(type) ({ \
struct type instance; \
type ## Init((struct type*) &instance); \
instance; \
})
struct User {
char name[50];
int age;
};
void UserInit(void* user) {
memcpy(((struct User*)user)->name, "Rahul\0", 6);
((struct User*)user)->age = 40;
}
struct Account {
char type[50];
double balance;
};
void AccountInit(void* account) {
memcpy(((struct Account*) account)->type, "Savings\0", 10);
((struct Account*) account)->balance = 10000000000.0;
}
int main() {
struct User user = STRUCT_INIT(User);
struct Account account = STRUCT_INIT(Account);
printf("%s\n", user.name);
printf("%d\n", user.age);
printf("%s\n", account.type);
printf("%f\n", account.balance);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment