我们可以有递归宏吗? [英] Can we have recursive macros?

查看:123
本文介绍了我们可以有递归宏吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在 C / C ++中使用递归宏?如果是,请提供一个示例。

I want to know if we can have recursive macros in C/C++? If yes, please provide a sample example.

第二件事:为什么我无法执行以下代码?我在做什么错误?是因为递归宏?

Second thing: why am I not able to execute the below code? What is the mistake I am doing? Is it because of recursive macros?

# define pr(n) ((n==1)? 1 : pr(n-1))
void main ()
{
    int a=5;
    cout<<"result: "<< pr(5) <<endl;
    getch();
}


推荐答案

只有预处理,而不是实际编译。如果你想在宏中找到一个问题,这是有用的。例如使用 g ++ -E

Your compiler probably provides an option to only pre-process, not actually compile. This is useful if you are trying to find a problem in a macro. For example using g++ -E:

> g++ -E recursiveMacro.c

# 1 "recursiveMacro.c"
# 1 "<built-in>"
# 1 "<command line>"
# 1 "recursiveMacro.c"

void main ()
{
    int a=5;
    cout<<"result: "<< ((5==1)? 1 : pr(5 -1)) <<endl;
    getch();
}

正如你所看到的,它不是递归的。 pr(x)在预处理期间只更换一次。重要的是要记住的是,所有的预处理器是盲目地用另一个替换一个文本字符串,它实际上不评估表达式(x == 1)

As you can see, it is not recursive. pr(x) is only replaced once during pre-processing. The important thing to remember is that all the pre-processor does is blindly replace one text string with another, it doesn't actually evaluate expressions like (x == 1).

您的代码无法编译的原因是 pr(5 -1)处理器,因此它在源代码中调用未定义的函数。

The reason your code will not compile is that pr(5 -1) was not replaced by the pre-processor, so it ends up in the source as a call to an undefined function.

这篇关于我们可以有递归宏吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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