function-pointer.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. * This is when I should start introducing typedefs
  15. */
  16. int
  17. add (int a, int b)
  18. {
  19. return a + b;
  20. }
  21. /* a function that takes a function pointer,
  22. and 3 values */
  23. int
  24. add3 (int (* pAdd)(int, int), int a, int b, int c)
  25. {
  26. return (pAdd) (a, b) + c;
  27. }
  28. int
  29. add4 (int (* pAdd3) (int (* pAdd) (int, int), int, int, int),
  30. int (* pAdd) (int, int),
  31. int a, int b, int c, int d)
  32. {
  33. return (pAdd3) (pAdd, a, b, c) + d;
  34. }
  35. int
  36. add5 (
  37. int (* pAdd4) (int (* pAdd3) ( int (* pAdd) (int, int), int, int, int ),
  38. int (*pAdd) (int, int),
  39. int, int, int, int),
  40. int (* pAdd3) ( int (* pAdd) (int, int), int, int, int ),
  41. int (* pAdd) (int, int),
  42. int a, int b, int c, int d, int e
  43. )
  44. {
  45. return (pAdd4) (pAdd3, pAdd, a, b, c, d) + e;
  46. }
  47. int
  48. main ()
  49. {
  50. int (* pAdd)(int, int);
  51. pAdd = &add;
  52. int sum = (pAdd) (5, 6);
  53. printf ("sum is %d\n", sum);
  54. /* pAdd is a function pointer */
  55. int sum3 = add3 (pAdd, 1, 2, 3);
  56. printf ("sum3 is %d\n", sum3);
  57. int (* pAdd3) (int (* pAdd) (int, int), int a, int b, int c);
  58. pAdd3 = &add3;
  59. sum3 = (pAdd3) (pAdd, 1, 2, 3);
  60. printf ("sum3 is still %d\n", sum3);
  61. int sum4 = add4 (pAdd3, pAdd, 1, 2, 3, 4);
  62. printf ("sum4 is %d\n", sum4);
  63. int (*pAdd4) ( int (* pAdd3) (int (* pAdd) (int, int), int, int, int),
  64. int (* pAdd) (int, int),
  65. int, int, int, int);
  66. pAdd4 = &add4;
  67. sum4 = (pAdd4) (pAdd3, pAdd, 1, 2, 3, 4);
  68. printf ("sum4 is still %d\n", sum4);
  69. int (*pAdd5) (int (* pAdd4) ( int (* pAdd3) (int (* pAdd) (int, int), int, int, int),
  70. int, int, int, int),
  71. int (* pAdd3) ( int (* pAdd) (int, int),
  72. int, int, int),
  73. int (* pAdd) (int, int),
  74. int, int, int, int, int);
  75. //pAdd5 = &add5;
  76. return 0;
  77. }