[英]Need to know good practice should i follow on below code
i have code as : 我的代码为:
int good_practice(void)
{
if (somethings == TRUE)
return true; //i am asked to remove it coz it will reach anyhow at end and do same but i feels it is good practice and why should i wait for end?
else
return false
}
}
return true;
}
i am asked remove first return since it will ultimately reach end of function and will return true.Is this good ? 我被要求删除第一个返回值,因为它最终将到达函数的结尾并返回true。这好吗?
what i feel why do i need to wait for cpu to go at end of function and return though i can do early.if i have decide to return with some condition why should i return from end why not there itself why to wait for end ? 我觉得为什么我需要等待cpu在函数结束时返回并尽早返回。如果我决定以某种条件返回,为什么我应该从结尾返回,为什么本身不为什么要等待结尾?
And also if i am wait for end the i increase time complexity(i know it won't make any difference) but no of instruction is also increased. 而且如果我在等待结束,我会增加时间复杂度(我知道这不会有任何区别),但是指令的增加也不会增加。
please help me to get out of this confusion? 请帮助我摆脱这种困惑?
This is called an “early return” and I don't think there is a clear consensus. 这被称为“早期回报”,我认为没有明确的共识。
Pros: 优点:
Cons: 缺点:
There are some similar previous questions about early returns, see here for example . 以前有一些关于提早回报的类似问题,例如 , 请参见此处 。
You are asked to remove the first return true
because you can simply check like this, and not have an additional redundant return true
: 要求您删除第一个
return true
因为您可以像这样简单地检查,而没有额外的冗余return true
:
int good_practice(void) {
if(!somethings) {
return false;
}
return true;
}
Anyway, the code in question is pretty much redundant . 无论如何,所讨论的代码几乎是多余的 。
You can replace it with an even better version, like this: 您可以用更好的版本替换它,如下所示:
int good_practice(void)
{
return somethings;
}
About the early return: 关于提前归还:
Its generally better to have one return at the end, because the performance gained, when returning earlier is nowhere near the gained readability by having one return only . 通常最好在末尾有一个返回,因为在更早返回时获得的性能与仅通过返回一个返回的可读性相差甚远。
(Thats just my own experience though). (尽管那只是我自己的经验)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.