ceedee
ceedee

Reputation: 237

How to add a statement at the end of a line containing a macro in C/C++?

To reduce the number of lines to be written, i am using macros in the following way:

#define FUNC(a, b)  func(a, b, threadId, sizeof(a)); \
                      do something 1;                 \
                      do something 2;    

This works well, as i just need to use the macro (with 2 parameters) that encodes the function call (with 4 parameters) and 2 or more other statements.

Problem arises when this function call is a parameter to another function. For example, suppose i need the following code:

func1(par1, func(a, b, c, d));
do something 1;
do something 2;

Is there a way to achieve this using macros, or any other alternatives? i.e. I am expecting something like:

func1(par1, FUNC(a, b)); //This statement(using macros) should transform into the above code after the preprocessing step. 

Upvotes: 0

Views: 279

Answers (2)

Jabberwocky
Jabberwocky

Reputation: 50883

I'm not sure what you are actually trying to achieve, but replacing this:

#define FUNC(a, b)  func(a, b, threadId, sizeof(a)); \
                  do something 1;                 \
                  do something 2;  

by this (assuming the type of the a and b parameters is int):

int FUNC(int a, int b)
{
  int returnvalue = func(a,b,threadId, sizeof(a));
  do something 1;
  do something 2;
  return returnvalue;
}

should do the job.

Upvotes: 3

Mircea
Mircea

Reputation: 19

You could try to isolate the code with brackets { }. But your idea is not one I would recommend, as the code becomes very hard to understand and debug.

#define FUNC(a, b) { func(a, b, threadId, sizeof(a)); \
                      do something 1;                 \
                      do something 2; }

But if you try to send this as a parameter to another function it still won't work because you are not returning anything to be uses as a parameter ( no adress, no value)

Upvotes: 0

Related Questions