使用变量与使用数字 [英] Using variable vs. using number

查看:82
本文介绍了使用变量与使用数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下那些版本的函数:

Imagine a function in those versions:

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,我在第一个中返回n,在第二个中返回1.结果是相同的,但是在忽略重要性的同时您还可以意识到其他任何区别吗?

The only difference is that I return n in the first and 1 in the second one, depending on n. The result is the same but is there any other difference you could be aware of while ignoring the significance?

我知道编译器很有可能会从中做出相同的汇编指令,但是,我很好奇.

I know there is a high chance the compiler will make the same assembly instructions out of it, but hey, I'm just curious.

推荐答案

正如评论中指出的, gcc会认出两者是相同的.对于clang对代码所做的操作,有一个后续问题.除了c声破坏外,区别还在于外观.

As has been pointed out in comments, gcc will recognise the two to be identical. For what clang does to the code there is a follow-up question. Apart from clang going havoc, the difference is cosmetic.

但是,您的代码中存在一个细微的问题. factorial(0)将使n-1环绕并递归,直到到达n==1为止,以返回错误的值:在顶级n==0调用中,从0 * faculty(-1U)返回0. (0!定义为1).

There is however a subtle problem in your code. factorial(0) will make n-1 wrap around and recurse till it arrives at n==1 just to return the wrong value: 0 from a 0 * faculty(-1U) in the top-level n==0 call. (0! is defined to be 1).

代码中的两个1是幻数,实际上它们是两个不同的数,它们恰好具有相同的值.一个是停止递归的条件,另一个是递归停止时返回的值.您选择了错误的停止条件.有些人可能会坚持认为,命名这些常量很愚蠢,但我认为这可能有助于发现该错误:

The two 1s in your code are magic numbers and actually they are two different ones, they just happen to have the same value. One is the condition to stop the recursion, the other is the value you return when recurstion stops. You chose the wrong stop condition. Some may insist that naming those constants is silly, but I think it could have helped to spot that mistake :

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);
}

魔术数字是代码中没有名称的数字.您有两个看起来相同的1,但是仔细检查发现这两个1实际上是有所不同的.减一很常见,我不认为这是魔术".与任何经验法则一样,您必须决定在何处应用它,而不是在何处应用.也许我不会在这样的简单"函数中命名常量.

Magic numbers are numbers in code without a name. You had two 1s that appeared to be the same, but close inspection shows that those two 1s are actually something different. In/decrementing by one is so common that I do not consider it as being "magic". As with any rule of thumb, you have to decide where to apply it and where not. Perhaps I wouldn't name the constants in such a "simple" function.

这篇关于使用变量与使用数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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