fork download
  1. #include <stdio.h>
  2.  
  3. /* Passing a function to itself */
  4.  
  5. /* Example 1 */
  6.  
  7. /* Choose a return type */
  8. typedef int example1_t;
  9.  
  10. /* Establish a function type with no parameter specification */
  11. typedef example1_t f_example1_any();
  12.  
  13. /* Establish the actual function type */
  14. typedef example1_t f_example1(f_example1_any *, int, double);
  15.  
  16. /* You can declare the upcoming function */
  17. f_example1 example1;
  18.  
  19. /* Definition */
  20. example1_t example1(f_example1_any * f, int i, double d) {
  21. /* Convert 'f' to the actual type */
  22. f_example1 * func = f;
  23.  
  24. (void) i;
  25. (void) d;
  26. /* Simple check */
  27. if (func == example1) {
  28. puts("example1: Passed ourself in the street");
  29. }
  30. return 0;
  31. }
  32.  
  33. /* Example 2 */
  34.  
  35. /* Choose a _unique_ return type */
  36. typedef struct { int ret; } example2_t;
  37.  
  38. /* Establish a function type with no parameter specification */
  39. typedef example2_t f_example2_any();
  40.  
  41. /* Establish the actual function type */
  42. typedef example2_t f_example2(f_example2_any *, int, double);
  43.  
  44. /* You can declare the upcoming function */
  45. f_example2 example2;
  46.  
  47. /* Definition */
  48. example2_t example2(f_example2_any * f, int i, double d) {
  49. example2_t result;
  50. /* Convert 'f' to the actual type */
  51. f_example2 * func = f;
  52.  
  53. (void) i;
  54. (void) d;
  55. /* Simple check */
  56. if (func == example2) {
  57. puts("example2: Passed ourself in the street");
  58. }
  59. return (result.ret = 0), result;
  60. }
  61.  
  62. /* Example 3 */
  63.  
  64. /* Use a function pointer wrapper */
  65. typedef struct s_example3 s_example3;
  66.  
  67. /* Establish the actual function type */
  68. typedef int f_example3(s_example3 *, int, double);
  69.  
  70. /* Complete the object type */
  71. struct s_example3 {
  72. f_example3 * func;
  73. };
  74.  
  75. /* You can declare the upcoming function */
  76. f_example3 example3;
  77.  
  78. /* Definition */
  79. int example3(s_example3 * f, int i, double d) {
  80.  
  81. (void) i;
  82. (void) d;
  83. /* Simple check */
  84. if (f->func == example3) {
  85. puts("example3: Passed ourself in the street");
  86. }
  87. return 0;
  88. }
  89.  
  90. /* Tests */
  91. int main(void) {
  92. s_example3 example3_wrapper = { example3 };
  93.  
  94. example1(example1, 42, 3.14159);
  95. example2(example2, 42, 3.14159);
  96. example3(&example3_wrapper, 42, 3.14159);
  97.  
  98. return 0;
  99. }
Success #stdin #stdout 0.02s 1720KB
stdin
Standard input is empty
stdout
example1: Passed ourself in the street
example2: Passed ourself in the street
example3: Passed ourself in the street