C宏功能越来越复杂

编程入门 行业动态 更新时间:2024-10-24 13:31:23
本文介绍了C宏功能越来越复杂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我见过的宏简单的例子,但想了解更复杂的东西,比方说用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)))

但同样,也有很多陷阱的,如不清楚运营商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宏功能越来越复杂

本文发布于:2023-10-31 06:32:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545298.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:功能

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!