Here is an example:
这是一个例子:
#define get_i() i
int i;
int i2;
i2 = get_i();
i2 = get_i();
In the case above ^^^ get_i()
acts like a function that returns something(the value ofi
in this case).
在上面的例子中,^^^ get_i()就像一个返回某些东西的函数(在这种情况下是值ofi)。
#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?
那可能吗?
1 个解决方案
#1
2
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.
这个技巧的缺点是你不能在这样的宏中创建临时变量。
#1
2
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.
这个技巧的缺点是你不能在这样的宏中创建临时变量。