function-pointer-with-typedefs.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #include <stdio.h>
  2. #include <string.h>
  3. /*
  4. * This is probably one of the silliest programs I've made.
  5. * I wanted to get a good grasp of C function pointers.
  6. * I started by making an add function. Then I made a pointer
  7. * to that add function, then I made an add3 function, which
  8. * has as one of it's parameters a pointer to add ().
  9. *
  10. * Then I made an add4 function, whose parameters include
  11. * a pointer to add3 () and a pointer to add ().
  12. *
  13. * It really starts getting complicated at that point.
  14. * That's why I made this program to see how easier it is to
  15. * make a program using typedefs.
  16. */
  17. // a new type "fpAdd" is a function pointer expecting two integers
  18. typedef int (*fpAdd) (int, int);
  19. // a new type "fpAdd3" is a function pointer, expecting a function pointer
  20. // of type fpAdd and three values.
  21. typedef int (* fpAdd3) (fpAdd, int, int, int);
  22. typedef int (* fpAdd4) (fpAdd3, fpAdd, int, int, int, int);
  23. typedef int (* fpAdd5) (fpAdd4, fpAdd3, fpAdd, int, int, int, int, int);
  24. int
  25. add (int a, int b)
  26. {
  27. return a + b;
  28. }
  29. /* a function that takes a function pointer,
  30. and 3 values */
  31. int
  32. add3 (fpAdd pAdd, int a, int b, int c)
  33. {
  34. return (pAdd) (a, b) + c;
  35. }
  36. int
  37. add4 (fpAdd3 pAdd3, fpAdd pAdd,
  38. int a, int b, int c, int d)
  39. {
  40. return (pAdd3) (pAdd, a, b, c) + d;
  41. }
  42. int
  43. add5 ( fpAdd4 pAdd4, fpAdd3 pAdd3, fpAdd pAdd,
  44. int a, int b, int c, int d, int e)
  45. {
  46. return (pAdd4) (pAdd3, pAdd, a, b, c, d) + e;
  47. }
  48. int
  49. main ()
  50. {
  51. // create a function pointer typedef
  52. fpAdd pAdd = &add;
  53. int sum = (pAdd) (1, 1);
  54. printf ("sum is %d\n", sum);
  55. /* pAdd is a function pointer */
  56. int sum3 = add3 (pAdd, 1, 2, 3);
  57. printf ("sum3 is %d\n", sum3);
  58. //int (* pAdd3) (fpAdd pAdd, int a, int b, int c);
  59. fpAdd3 pAdd3 = &add3;
  60. sum3 = (pAdd3) (pAdd, 1, 2, 3);
  61. printf ("sum3 is still %d\n", sum3);
  62. int sum4 = add4 (pAdd3, pAdd, 1, 2, 3, 4);
  63. printf ("sum4 is %d\n", sum4);
  64. //int (*pAdd4) ( fpAdd3 pAdd3, fpAdd pAdd, int, int, int, int);
  65. fpAdd4 pAdd4 = &add4;
  66. sum4 = (pAdd4) (pAdd3, pAdd, 1, 2, 3, 4);
  67. printf ("sum4 is still %d\n", sum4);
  68. fpAdd5 pAdd5 = &add5;
  69. int sum5 = (pAdd5) (pAdd4, pAdd3, pAdd, 1, 2, 3, 4, 5);
  70. printf("sum5 is %d\n", sum5);
  71. return 0;
  72. }