简体   繁体   English

为什么此递归程序有效?

[英]why does this recursion program work?

#include <iostream>

using namespace std;

int main() {
    int n,x;
    int fact(int);

    cin >> n;

    x = fact(n);

    cout << x;

    return 0;
}

int fact(int n) {
    if(n!=1)
        return n*fact(n-1);
}

In the last case, when the argument passed to the function fact is 1, how is it able to calculate that fact(1) is equal to 1, without me specifying it in my code? 在最后一种情况下,当传递给函数fact的参数为1时,如何在我无需在代码中指定的情况下计算出fact(1)等于1的情况?

This program relies on undefined behavior. 该程序依赖于未定义的行为。 It is certainly not guaranteed to work, but you may have found a situation in which the parameter you send (1) is in a place where the calling code perceives it as the return value. 当然不能保证它能正常工作,但是您可能会发现这样一种情况,您发送的参数(1)处于调用代码将其视为返回值的位置。 Do not depend on this behavior. 不要依赖此行为。

Many C++ compilers would reject this code as having a semantic issue: Not all control paths return a value from fact() 许多C ++编译器会因为存在语义问题而拒绝此代码: 并非所有控制路径都从fact()返回值

 int fact(int n); 

This function signature returns an integer, but when n=1 is given there is no corresponding return statement in your implementation. 此函数签名返回一个整数,但是当给定n = 1时,您的实现中没有相应的return语句。 In that case, the function may return any int value (ie garbage in memory) and the behaviour is undefined . 在那种情况下,该函数可能返回任何int值(即内存中的垃圾),并且该行为是undefined You should not depend on this, even though your compiler allows it to run. 即使编译器允许运行它,也不应依赖于此。

I'm quite certain you saw a warning when compiling your program. 我很确定您在编译程序时看到了警告。 In my environment (g++ on Mac OSX), the compiler issued the following warning: 在我的环境中(在Mac OSX上为g ++),编译器发出以下警告:

warning: control may reach end of non-void function [-Wreturn-type] 警告:控制可能会达到非无效功能的结束[-Wreturn-type]

Personally, I don't think there is any good reason for a compiler to allow this kind of bug (ie it should fail to compile). 就个人而言,我认为编译器没有充分的理由允许这种错误(即,它应该无法编译)。

Reference: A similar question is found below: 参考:以下是类似的问题:

C++ return value without return statement 没有返回语句的C ++返回值

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

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