annotate 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
rev   line source
lindquist@270 1 extern(C) int printf(char*, ...);
lindquist@270 2
lindquist@1 3 int return_six()
lindquist@1 4 {
lindquist@1 5 return 6;
lindquist@1 6 }
lindquist@1 7
lindquist@1 8 int add_int(int a, int b)
lindquist@1 9 {
lindquist@1 10 return a+b;
lindquist@1 11 }
lindquist@1 12
lindquist@1 13 int sub_int(int a, int b)
lindquist@1 14 {
lindquist@1 15 return a-b;
lindquist@1 16 }
lindquist@1 17
lindquist@1 18 alias int function(int,int) binfn_t;
lindquist@1 19
lindquist@1 20 int binop_int(binfn_t op, int a, int b)
lindquist@1 21 {
lindquist@1 22 return op(a,b);
lindquist@1 23 }
lindquist@1 24
lindquist@1 25 binfn_t get_binop_int(char op)
lindquist@1 26 {
lindquist@1 27 binfn_t fn;
lindquist@1 28 if (op == '+')
lindquist@1 29 fn = &add_int;
lindquist@1 30 else if (op == '-')
lindquist@1 31 fn = &sub_int;
lindquist@1 32 return fn;
lindquist@1 33 }
lindquist@1 34
lindquist@1 35 extern(C) float mul_float(float a, float b)
lindquist@1 36 {
lindquist@1 37 return a * b;
lindquist@1 38 }
lindquist@1 39
lindquist@1 40 void function_pointers()
lindquist@1 41 {
lindquist@1 42 int function() fn = &return_six;
lindquist@1 43 assert(fn() == 6);
lindquist@1 44
lindquist@1 45 binfn_t binfn = &add_int;
lindquist@1 46 assert(binfn(4,1045) == 1049);
lindquist@102 47
lindquist@1 48 assert(binop_int(binfn, 10,656) == 666);
lindquist@102 49
lindquist@1 50 binfn = get_binop_int('+');
lindquist@1 51 assert(binop_int(binfn, 10,100) == 110);
lindquist@1 52 binfn = get_binop_int('-');
lindquist@1 53 assert(binop_int(binfn, 10,100) == -90);
lindquist@102 54
lindquist@1 55 {
lindquist@1 56 auto ffn = &mul_float;
lindquist@1 57 float ftmp = mul_float(2.5,5);
lindquist@1 58 assert(ftmp == 12.5);
lindquist@1 59 assert(ftmp > 12.49 && ftmp < 12.51);
lindquist@1 60 }
lindquist@1 61 }
lindquist@1 62
lindquist@1 63 void main()
lindquist@1 64 {
lindquist@1 65 printf("Function pointer test\n");
lindquist@1 66 function_pointers();
lindquist@1 67 printf(" SUCCESS\n");
lindquist@1 68 }