ADT
aaron-thesis
arm-eh
ast-experimental
cleanup-dtors
deferred_resn
enum
forall-pointer-decay
jacob/cs343-translation
jenkins-sandbox
new-ast
new-ast-unique-expr
no_list
persistent-indexer
pthread-emulation
qualifiedEnum
Last change
on this file since 4075228 was 4075228, checked in by Aaron Moss <a3moss@…>, 7 years ago |
Start generics chapter of thesis, add code examples of C polymorphic types
|
-
Property mode
set to
100644
|
File size:
886 bytes
|
Line | |
---|
1 | #include <stdlib.h>
|
---|
2 | #include <stdio.h>
|
---|
3 |
|
---|
4 | // code is nested in macros
|
---|
5 |
|
---|
6 | #define list(N) N ## _list
|
---|
7 |
|
---|
8 | #define list_insert(N) N ## _list_insert
|
---|
9 |
|
---|
10 | #define list_head(N) N ## _list_head
|
---|
11 |
|
---|
12 | #define define_list(N, T) \
|
---|
13 | struct list(N) { T value; struct list(N)* next; }; \
|
---|
14 | \
|
---|
15 | void list_insert(N)( struct list(N)** ls, T x ) { \
|
---|
16 | struct list(N)* node = malloc(sizeof(struct list(N))); \
|
---|
17 | node->value = x; node->next = *ls; \
|
---|
18 | *ls = node; \
|
---|
19 | } \
|
---|
20 | \
|
---|
21 | T list_head(N)( const struct list(N)* ls ) { return ls->value; }
|
---|
22 |
|
---|
23 | define_list(int, int); // defines int_list
|
---|
24 | define_list(string, const char*); // defines string_list
|
---|
25 |
|
---|
26 | // use is efficient, but syntactically idiosyncratic
|
---|
27 |
|
---|
28 | int main() {
|
---|
29 | struct list(int)* il = NULL;
|
---|
30 | list_insert(int)( &il, 42 );
|
---|
31 | printf("%d\n", list_head(int)(il));
|
---|
32 |
|
---|
33 | struct list(string)* sl = NULL;
|
---|
34 | list_insert(string)( &sl, "hello" );
|
---|
35 | printf("%s\n", list_head(string)(sl) );
|
---|
36 | }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.