c++ - 使用变量与使用数字

标签 c++ c assembly

想象一下这些版本中的函数:

int faculty(const unsigned int n) {
    return n == 1 ? n : n * faculty(n - 1);
}
int faculty(const unsigned int n) {
    return n == 1 ? 1 : n * faculty(n - 1);
}

唯一的区别是,我在第一个中返回 n,在第二个中返回 1,具体取决于 n。结果是相同的,但是在忽略重要性的同时您是否可以意识到任何其他差异?

我知道编译器很有可能会从中生成相同的汇编指令,但是嘿,我只是好奇。

最佳答案

正如评论中所指出的,gcc will recognise the two to be identical 。对于 clang 对代码的作用,有一个 follow-up question 。除了 clang 造成严重破坏之外,区别只是表面上的。


但是您的代码中存在一个微妙的问题。 factorial(0) 将使 n-1 环绕并递归,直到到达 n==1 只是返回错误的值:0 来自顶级 n==0 调用中的 0 * coach(-1U)。 (0! 被定义为 1)。

这是一个过于冗长的正确版本:

int faculty(const unsigned int n) {
    const unsigned int stop_when_n_leq = 1;
    const int return_at_stop = 1;
    return n <= stop_when_n_leq ? return_at_stop : n * faculty(n - 1);
}

关于c++ - 使用变量与使用数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60773397/

相关文章:

c - QuickSort C 中位数枢轴元素

assembly - 编译器在这段汇编代码中做了什么?

c++ - 根据模板参数有条件地定义模板类的构造函数

c++ - C++中指向字符数组的指针

c++ - 我传递采用 char* 的 tinyxml 函数的是什么 unicode 格式?

c - 使用数组创建单链表时的警告

c++ - 同一系统上的两个版本的 glibc

c - 在先前 malloc ed 指针上使用 realloc 会导致段错误

c - 如何将C语言转换为MIPS汇编代码?

assembly - 未处理的异常 : Recursive Factorial in assembly (MASM)