2

Version 1:

int abc(...)
{
    if(a || b || c))
        return 1;
    else
        return 0;
}

Version 2:

int abc(...)
{
    if(a || b || c))
        return 1;

    return 0;
}

Is there any difference? Which code is the proper one?

Danijel
  • 8,198
  • 18
  • 69
  • 133
  • 6
    There is no difference, I prefer `return (a || b || c);` – David Ranieri May 27 '20 at 08:19
  • 1
    No difference at all. – Alex Lop. May 27 '20 at 08:19
  • 1
    The difference is only in which version matches the coding styles/habits in your environment. Easily in one company any of them can be "wrong". – Yunnosch May 27 '20 at 08:20
  • Does this answer your question? [Unnecessary 'else' after 'return'. (No-else-return)](https://stackoverflow.com/questions/46875442/unnecessary-else-after-return-no-else-return) Different language, agreed, but the concept is the same. – Yunnosch May 27 '20 at 08:22
  • 1
    In this case it makes no difference, as the others have already said. However i would like to add that, in a more complicated function, your "version 2" style can potentially make it hard to follow the control-flow (for example when there are `return` statements buried deep in some nested `if` clauses). In other words: in some cases it can help readability to have all return statements at the same "level" (or have just one single return statement instead of multiple ones) – Felix G May 27 '20 at 08:51
  • 1
    See also: https://softwareengineering.stackexchange.com/questions/157407/best-practice-on-if-return and https://softwareengineering.stackexchange.com/questions/375297/if-and-else-or-if-and-return – Cody Gray - on strike May 27 '20 at 09:12
  • 1
    The closing of this question is discussed at Stack Overflow Meta [here](https://meta.stackoverflow.com/questions/397791/is-it-appropriate-to-close-a-question-as-duplicate-of-another-language-one). Feel free to participate. – RobertS supports Monica Cellio May 27 '20 at 09:50

3 Answers3

3

There is no difference since, upon returning 1, no further code in the function is executed anyway, and one of the paths must be chosen.

I prefer the latter since it involves less typing but that's really just a matter of preference.

Of course, there are other options as well such as the simpler:

return a || b || c;
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
3

"Is there any difference?"

No.

"Which code is the proper one?"

None. They are equivalent. Note if the else isn´t explicitly needed for the context, omit it since it is redundant:

Unnecessary 'else' after 'return'. (No-else-return)

Note: The linked question is for Javascript, but it shares the same concern of yours.


Furthermore, your code could be simplified:

int abc (...)
{
    return (a || b || c);
}

If the condition is true 1, else 0 is returned.

1

Both code variants are the same and will generate same assembly instructions.
But more elegant way is:

int abc(...)
{
    return (a || b || c);
}
Aleksey
  • 775
  • 5
  • 14