Hairi Hairi - 1 year ago 70
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 ^^^
acts like a function that returns something(the value of
in this case).

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

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download