Last change
on this file since 9476549 was
48b7085e,
checked in by Aaron Moss <a3moss@…>, 6 years ago
|
Start into generic types design in thesis
|
-
Property mode set to
100644
|
File size:
986 bytes
|
Rev | Line | |
---|
[4075228] | 1 | #include <stdlib.h> |
---|
| 2 | #include <stdio.h> |
---|
| 3 | |
---|
| 4 | struct int_list { int value; struct int_list* next; }; |
---|
| 5 | |
---|
| 6 | void 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 | |
---|
| 12 | int int_list_head( const struct int_list* ls ) { return ls->value; } |
---|
| 13 | |
---|
| 14 | // all code must be duplicated for every generic instantiation |
---|
| 15 | |
---|
| 16 | struct string_list { const char* value; struct string_list* next; }; |
---|
| 17 | |
---|
| 18 | void 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 | |
---|
| 24 | const char* string_list_head( const struct string_list* ls ) |
---|
| 25 | { return ls->value; } |
---|
| 26 | |
---|
| 27 | // use is efficient and idiomatic |
---|
| 28 | |
---|
| 29 | int 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" ); |
---|
[48b7085e] | 36 | printf("%s\n", string_list_head(sl)); |
---|
[4075228] | 37 | } |
---|
Note: See
TracBrowser
for help on using the repository browser.