简体   繁体   English

C宏用于更复杂的功能

[英]C Macros for more complex functions

I've seen simple examples of macros, but wondering about something more complex, say with if statements and reassigning given variables. 我看过一些简单的宏示例,但是想知道更复杂的事情,比如说if语句并重新分配给定的变量。 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. 我有一个将要运行数十亿次的函数,因此最好让预处理器将代码扔在那里,而不是来回传递变量。

Say I have the following function: 说我有以下功能:

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? 如何将其变成宏?

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! 请注意,宏与函数调用并不相同-宏实际上代替了使用C语言的源代码,而不是调用和返回-因此,可能会有很多意外行为! Your example could be made into a macro like so: 您的示例可以做成这样的宏:

#define FOO(a,b,c)((a)+(b)+(((b)>3)?(b):((a)>2)?(a):(c)))

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. 最好是听取其他答案的建议,并使用复杂的宏以外的其他策略。

Easy - don't use macros - just use inline functions: 简单-不使用宏-只需使用内联函数:

__inline int foo(int a, int b, int c)
{  
    if (a > 2)  
        c = a;  
    if (b > 3)  
        c = b;  
    return a + b + c;  
}

Whilst you could replace your function with a macro, in all likelihood, it will make no difference to the performance. 尽管您可以用宏替换函数,但是这对性能没有任何影响。 Any reasonable compiler will have moved the function inline if it it thinks it will help. 任何合理的编译器如果认为有帮助,都可以将函数直接内联。

If it looks like it should be a function, then make it a function. 如果看起来它应该是一个函数,则使其成为一个函数。

Compiler technology has become good enough over time, so you don't have to worry about stuff like this. 随着时间的推移,编译器技术已经变得足够好,因此您不必担心这种事情。 Have trust in your compiler and you should be fine. 信任您的编译器,您应该会很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM