如果if包含返回,我应该使用else吗?

PBG*_*PBG 0 syntax

我正在阅读本书中的一些例子,并且我注意到有两种不同的约定,用于具有各种返回条件.这两者有什么区别吗?

//example 1
if(someCondition)
{
   return (someValue);
}
return (someOtherValue);

//example 2
if(someCondition)
{
   return (someValue);
}
else
{
   return (someOtherValue);
}
Run Code Online (Sandbox Code Playgroud)

就个人而言,我更喜欢第二个例子,因为它更明确,我觉得它更具可读性.

Cha*_*ion 6

如果您的语言包含条件运算符,我建议使用它.

return condition ? ifTrue : ifFalse;
Run Code Online (Sandbox Code Playgroud)