功能类似于C中的宏 [英] Function like Macros in C

查看:94
本文介绍了功能类似于C中的宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试理解宏(Macros)之类的函数的概念,但是有几点使我迷惑不解.例如说我们有:

I am trying to understand the idea of function like Macros however there are a few points that befuddle me. For example say we have:

#define Max(a,b)  ((a)>(b)) ? (a):(b))

我这样称呼

int i = Max(4,5);

这将评估等于a>b的条件表达式吗?如果是,则为a,否则为b.但是我对Max函数如何知道如何处理参数感到困惑.与实际功能不同,实现不是在调用程序中的代码中编写的. define语句右边的语句对我有用吗?对我来说这只是新事物,我想确保自己了解这里发生的事情.

This will evaluate a conditional expression equivalent to a>b? If yes then a, else b. But I'm confused as to how the Max function knows what to do with the arguments. Unlike an actual function, the implementation isn't written in code in the calling program. is the statement to the right of the define statement doing this for me? Its just a new thing for me and I want to make sure I understand what is happening here.

函数的这一特定部分(例如宏)使我感到困惑.我知道这些类型的宏对于减少开销成本很有用,因为它们排除了JSR RTS处理器指令,从而节省了堆栈上的内存.

This particular part of function like macros confuses me. I know that these types of macros are useful for reducing overhead costs since they exclude the JSR RTS processor instructions which saves memory on the stack.

推荐答案

#define Max(a,b)  ((a)>(b)) ? (a):(b))

是一个宏,除了在代码中进行简单的文本替换外,不会导致其他任何事情,这意味着在预处理此行期间:

is a macro, that causes nothing else but a simple textual replacement within your code, which means that during the preprocessing this line:

int i = Max(4,5);

更改为:

int i = ((4)>(5)) ? (4):(5));

请注意,使用此类宏时没有类型安全性,并且调试代码也将非常困难.好的经验法则是: 在可以通过功能实现相同效果的情况下不要使用宏 :

Note that there is no type safety while working with macros like this one and you will have really hard time while debugging your code as well. Good rule of thumb is: Don't use macro when you can achieve the same with function:

int max(int a, int b) {
    return (a > b) ? a : b;
}

这篇关于功能类似于C中的宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆