C宏功能越来越复杂 [英] C Macros for more complex functions
问题描述
我见过的宏简单的例子,但想了解更复杂的东西,比方说用if语句和重新分配给变量。可以更复杂的前pressions这样在宏来完成?我有一个会运行数十亿次的函数,因此它会很高兴有preprocessor只是扔code在那里,而不是传递变量来回。
I've seen simple examples of macros, but wondering about something more complex, say with if statements and reassigning given variables. Can more complex expressions like this be done in a macro? I've got a function that'll be run billions of times, so it would nice to have the preprocessor just throw the code in there rather than passing variables back and forth.
说我有以下功能:
int foo(int a, int b, int c){
if (a > 2)
c = a;
if (b > 3)
c = b;
return a + b + c;
}
我怎样才能使这成为宏?
How can I make this into a macro?
推荐答案
注意宏不一样的函数调用 - 宏实际上取代C源$ C $ c其中它们用于调用和返回,而不是 - 所以可以有很多意想不到的行为!您的例子可以做成一个宏像这样:
Note that macros aren't the same as function calls - macros actually replace the C source code where they are used instead of calling and returning - so there can be a lot of unexpected behavior! Your example could be made into a macro like so:
#define FOO(a,b,c)((a)+(b)+(((b)>3)?(b):((a)>2)?(a):(c)))
但同样,也有<一个href=\"http://www.brainbell.com/tutors/c/Advice_and_Warnings_for_C/Macros_and_Miscellaneous_Pitfalls.html\"相对=使用复杂的宏时,nofollow的>很多陷阱的,如不清楚运营商precedence和重复自动递增/递减操作符。
But again, there are many pitfalls when using complex macros, such as unclear operator precedence and duplicated auto-increment/decrement operators.
这也可能是最好的倾听其他答案的建议,使用替代战略不是复杂的宏。
It's probably best to heed the advice of other answers and use alternative strategies than complex macros.
这篇关于C宏功能越来越复杂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!