Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Pass Simple, Anonymous Functions as Parameters in C

Tags:

c

I'm sure some variation of this question has been asked before but all other, similar questions on SO seem to be much more complex, involving passing arrays and other forms of data. My scenario is much simpler so I hope there is a simple/elegant solution.

Is there a way that I can create an anonymous function, or pass a line of code as a function pointer to another function?

In my case, I have a series of diverse operations. Before and after each line of code, there are tasks I want to accomplish, that never change. Instead of duplicating the beginning code and ending code, I'd like to write a function that takes a function pointer as a parameter and executes all of the code in the necessary order.

My problem is that it's not worth defining 30 functions for each operation since they are each one line of code. If I can't create an anonymous function, is there a way that I can simplify my C code?

If my request isn't entirely clear. Here's a bit of pseudo-code for clarification. My code is much more meaningful than this but the code below gets the point accross.

void Tests()
{
  //Step #1
  printf("This is the beginning, always constant.");
  something_unique = a_var * 42;  //This is the line I'd like to pass as an anon-function.
  printf("End code, never changes");
  a_var++;

  //Step #2
  printf("This is the beginning, always constant.");
  a_diff_var = "arbitrary";  //This is the line I'd like to pass as an anon-function.
  printf("End code, never changes");
  a_var++;

  ...
  ...

  //Step #30
  printf("This is the beginning, always constant.");
  var_30 = "Yup, still executing the same code around a different operation.  Would be nice to refactor...";  //This is the line I'd like to pass as an anon-function.
  printf("End code, never changes");
  a_var++;
}
like image 410
RLH Avatar asked Aug 10 '11 16:08

RLH


2 Answers

Not in the traditional sense of anonymous functions, but you can macro it:

#define do_something(blah) {\
    printf("This is the beginning, always constant.");\
    blah;\
    printf("End code, never changes");\
    a_var++;\
}

Then it becomes

do_something(something_unique = a_var * 42)
like image 56
Foo Bah Avatar answered Oct 13 '22 00:10

Foo Bah


No, you cannot. Anonymous functions are only available in functional languages (and languages with functional subsets), and as we all know, c is dysfunctional ;^)

like image 36
Nate Avatar answered Oct 13 '22 00:10

Nate