Mercurial > projects > ldc
comparison tests/mini/funcptr.d @ 341:1bb99290e03a trunk
[svn r362] Started merging the old 'test' dir as well as the newer 'tangotests' dir into 'tests/mini' and 'tests/minicomplex'.
author | lindquist |
---|---|
date | Sun, 13 Jul 2008 02:51:19 +0200 |
parents | test/funcptr.d@d9d5d59873d8 |
children |
comparison
equal
deleted
inserted
replaced
340:351c0077d0b3 | 341:1bb99290e03a |
---|---|
1 extern(C) int printf(char*, ...); | |
2 | |
3 int return_six() | |
4 { | |
5 return 6; | |
6 } | |
7 | |
8 int add_int(int a, int b) | |
9 { | |
10 return a+b; | |
11 } | |
12 | |
13 int sub_int(int a, int b) | |
14 { | |
15 return a-b; | |
16 } | |
17 | |
18 alias int function(int,int) binfn_t; | |
19 | |
20 int binop_int(binfn_t op, int a, int b) | |
21 { | |
22 return op(a,b); | |
23 } | |
24 | |
25 binfn_t get_binop_int(char op) | |
26 { | |
27 binfn_t fn; | |
28 if (op == '+') | |
29 fn = &add_int; | |
30 else if (op == '-') | |
31 fn = &sub_int; | |
32 return fn; | |
33 } | |
34 | |
35 extern(C) float mul_float(float a, float b) | |
36 { | |
37 return a * b; | |
38 } | |
39 | |
40 void function_pointers() | |
41 { | |
42 int function() fn = &return_six; | |
43 assert(fn() == 6); | |
44 | |
45 binfn_t binfn = &add_int; | |
46 assert(binfn(4,1045) == 1049); | |
47 | |
48 assert(binop_int(binfn, 10,656) == 666); | |
49 | |
50 binfn = get_binop_int('+'); | |
51 assert(binop_int(binfn, 10,100) == 110); | |
52 binfn = get_binop_int('-'); | |
53 assert(binop_int(binfn, 10,100) == -90); | |
54 | |
55 { | |
56 auto ffn = &mul_float; | |
57 float ftmp = mul_float(2.5,5); | |
58 assert(ftmp == 12.5); | |
59 assert(ftmp > 12.49 && ftmp < 12.51); | |
60 } | |
61 } | |
62 | |
63 void main() | |
64 { | |
65 printf("Function pointer test\n"); | |
66 function_pointers(); | |
67 printf(" SUCCESS\n"); | |
68 } |