Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parentheses around return values - why?

Tags:

java

c++

c

Quite often I see code like this (C, C++ and sometimes Java):

return (value);

I don't see any benefit of these parentheses. So my question is, have the programmers assumed return to be some kind of function with the return value as argument or are there really cases where these parentheses make sense?

I understand that a similar question has already been asked here, but this is related to ANSI C only. I wonder if there are aspects specific to C++ or Java that have not been answered there.

like image 802
Frank Puffer Avatar asked Feb 22 '16 17:02

Frank Puffer


1 Answers

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.
like image 136
Haris Avatar answered Sep 18 '22 15:09

Haris