source: doc/theses/aaron_moss_PhD/phd/code/bespoke-generic.c @ 4075228

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resnenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprno_listpersistent-indexerpthread-emulationqualifiedEnum
Last change on this file since 4075228 was 4075228, checked in by Aaron Moss <a3moss@…>, 6 years ago

Start generics chapter of thesis, add code examples of C polymorphic types

  • Property mode set to 100644
File size: 987 bytes
RevLine 
[4075228]1#include <stdlib.h>
2#include <stdio.h>
3
4struct int_list { int value; struct int_list* next; };
5
6void int_list_insert( struct int_list** ls, int x ) {
7        struct int_list* node = malloc(sizeof(struct int_list));
8        node->value = x; node->next = *ls;
9        *ls = node;
10}
11
12int int_list_head( const struct int_list* ls ) { return ls->value; }
13
14// all code must be duplicated for every generic instantiation
15
16struct string_list { const char* value; struct string_list* next; };
17
18void string_list_insert( struct string_list** ls, const char* x ) {
19        struct string_list* node = malloc(sizeof(struct string_list));
20        node->value = x; node->next = *ls;
21        *ls = node;
22}
23
24const char* string_list_head( const struct string_list* ls )
25        { return ls->value; }
26
27// use is efficient and idiomatic
28
29int main() {
30        struct int_list* il = NULL;
31        int_list_insert( &il, 42 );
32        printf("%d\n", int_list_head(il));
33       
34        struct string_list* sl = NULL;
35        string_list_insert( &sl, "hello" );
36        printf("%s\n", string_list_head(sl) );
37}
Note: See TracBrowser for help on using the repository browser.