Hairi Hairi - 1 month ago 7
C Question

Can I really make a function like macro

Here is an example:

#define get_i() i
int i;
int i2;


i2 = get_i();


In the case above ^^^
get_i()
acts like a function that returns something(the value of
i
in this case).

#define set_i(value) do{i = (value);}while(0)
set_i(i2);


This ^^^ above acts like a function that DO NOT return.

My question is, can I use macros to create a function-like macro that can both, do something, and return an object? Here is a pseudo code:

#define increse_i2_and_return_i() i2++; return i;


Is that possible?

Answer

You can use comma operator for that. The value of the last operand will be the value of an entire expression.

#define increse_i2_and_return_i() (i2++, i)

The downside of this trick is that you can't create temporary variables in a such macro.

Comments