Parentheses around return values - why?

With respect to C

Parentheses are put where there is an expression and one wants the return value to be that value of the expression. Even then parentheses are not needed. It is completely ok to write something like

return x + y;

Programmers do make it return (x + y); to make it more readable.

So, putting parentheses is a matter of opinion and practice.


With respect to C++

There is an arcane case where parentheses matters. Quoting this question

int var1 = 42;
decltype(auto) func1() { return var1; } // return type is int, same as decltype(var1)
decltype(auto) func1() { return(var1); } // return type is int&, same as decltype((var1))

You can see the returned values are different, and that is due to the parentheses. You can go through this answer to understand in detail.


With respect to java, parentheses does not make any difference.

Coding convention suggests to go with

return x + y;

to understand more, read this answer.


NOTE: I do not know much about java and C++. All of the content in my answer about java and C++ are taken from other answers. I did this to consolidate the different conventions for the three languages.

Technically, there's no reason to parenthesize the expression given to return. It's a matter of taste really.

That said, I'll typically parenthesize a return expression if it uses boolean operators. Since such operators are typically seen as part of a while or if, it makes it more clear that you want to do something with that value besides jumping in my opinion.

int out_of_range(int x)
{
    return ((x < 1) || (x > 10));
}

Tags:

C++

C

Java