Skip to content

Instantly share code, notes, and snippets.

@wrongbyte
Created February 19, 2022 20:40
Show Gist options
  • Save wrongbyte/05e179dc0fae44a08953ede386a7b934 to your computer and use it in GitHub Desktop.
Save wrongbyte/05e179dc0fae44a08953ede386a7b934 to your computer and use it in GitHub Desktop.
structs em C, algo meio object oriented idk
// ref from https://www.alicemaz.com/writing/program.html
// it gets easier to reason about structs being only a definition of how much space we need to allocate for a "composite" data type.
typedef struct Android Android;
struct Android {
char *name;
char *secret_name;
unsigned int kills;
bool on_mission;
};
Android a_two = { "A2", "No2", 972, true }; // stack-allocated struct
// below is like initiating an instance of an object
Android* make_android(char *name, char *secret_name) {
Android *a = malloc(sizeof(Android));
a->name = name;
a->secret_name = secret_name;
a->kills = 0;
a->on_mission = false;
return a;
}
// stack-allocated pointers to heap-allocated structs, they can be accessed as
//long as a copy of the pointer is retained somewhere and are never deallocated
//unless explicitly freed
Android *two_b = make_android("2B", "2E");
Android *nine_s = make_android("9S", NULL);
// we can modigy them on the fly
two_b->on_mission = true;
two_b->kills++;
// but modifying structs on the fly is complicated because of potential concurrency and bugs
// therefore we will have to find a way to check the conditions, before modifying data.
int go_on_mission(Android *a) {
if(a->onmission) {
fprintf(stderr, "%s is already on a mission!\n", a->name);
return 1;
}
a->on_mission = true;
return 0;
}
void score_kill(Android *a, bool was_friendly) {
if(was_friendly) {
printf("redacting combat logs...\n");
}
else {
a->kills++;
}
}
go_on_mission(two_b);
score_kill(two_b, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment