How to pass into a macro different functions with different parameres.

I have a piece of identical code that need to be executed in several places of a program. The only difficulty is that within this code I need to call different function with different parameters (both type and number are different) specific to that place in the program. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/* PLACE ONE */
do{
   int x = 1; int y = 2;
   if(condition1)
   {
      function_one(param1, param2,  x,  y, param3);
   }
   //some other code here
   if(condition2)
   {
      function_one(NULL, NULL, x, y, NULL);
   }
}
while(condition0)

/* PLACE TWO */
do{
   int x = 1; int y = 2;
   if(condition1)
   {
      function_two(param4, param5, param6, param7, x, y, param8, param9);
   }
   //some other code here
   if(condition2)
   {
      function_two(NULL, NULL, NULL, NULL, x, y, NULL, NULL);
   }
}
while(condition0)


Is it possible to have this code only in one place and just reference to it from all those places when it need to be executed? How can I possibly solve this problem?
Thanks.
Last edited on
You could use something like this:
1
2
3
4
5
6
7
8
9
10
11
12
#define F(x) if (1==1){\
	x;\
}

void f(int a,int b){
	a+=b;
}

int main(){
	F(f(1,2));
	return 0;
}
Function pointers :)
But as I said in PLACE ONE a function is taking five parameters for instance, in PLACE TWO a function is taking eight parameters in other places it could be seven or seventeen. And of course the type of the parameters will be different as well.
Therefore the macro you posted would not cater for this purpose because it takes predefined number and type of parameters.
Thanks.
Ahh! But you can also do this!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#define F(x,y,z) if (y==z){\
	x;\
}

void f(int a,int b){
	a+=b;
}

void f(int a,int b,int c){
	a+=b+c;
}

int main(){
	F(f(1,2),1,1);
	F(f(1,2,3),1,1);
	return 0;
}
Last edited on
To Zaita - do you have any suggestions how can I implement use of function pointers in this case? Because that was the idea in first place.
Thanks.
Thanks helios, that's interesting idea.
Hi Zaita, I read the article you suggested - very interesting. My problem is that all the parameters would be pointers to different wrapper objects. Is there a possibility to bind them together in some sort of standard data structure i.e. array, list or vector?
What you are trying to do sounds suspect to me. You should re-think how you want to make your program's logic work.

Only if you absolutely must go this route, there are several solutions available to you. Just off the top of my head:

Heterogeneous lists http://www.devx.com/cplus/10MinuteSolution/29757

Or wrap your data/function calls into a global class type that knows how to call which with what.

Good luck!
Topic archived. No new replies allowed.