Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parenthesis surrounding return values in C

Quite often in ANSI C code I can see parenthesis sorrounding a single return value.

Like this:-

int foo(int x) {   if (x)     return (-1);   else     return (0); } 

Why use () around the return value in those cases? Any ideas? I can see no reason for that.

like image 501
Tooony Avatar asked Oct 02 '08 11:10

Tooony


People also ask

What does parentheses do in C?

Using parentheses defensively reduces errors and, if not taken to excess, makes the code more readable. Subclause 6.5 of the C Standard defines the precedence of operation by the order of the subclauses.

Does return need parenthesis?

So basically return is a statement with an optional expression list as an argument. Therefore parentheses are not required and only preferrable when necesary (i.e. for breaking precedences).

What is return type in C?

Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void. Function Name − This is the actual name of the function.

Why do we use return 0 in C programming?

C++ return 0 in the main function means that the program executed successfully. return 1 in the main function means that the program does not execute successfully and there is some error.


1 Answers

There really isn't a reason...it's just old convention.

To save space, programmers would often do the final math in the return line instead of on it's own line and the parens ensure are mostly there to make it easier to see that it is a single statement that is returned, like this:

return (x+i*2); 

instead of

int y = x+i*2; return y; 

The parenthesis became a habit and it stuck.

like image 160
Adam Haile Avatar answered Sep 29 '22 14:09

Adam Haile