return

What's the difference between this...

int someFunction(){
return number;
}

...and this...

int someFunction(){
return(number);
}
Parantheses around the operand of the return statement:

C++98: There is no difference. The operand of the return statement is an expression. And:
A parenthesized expression (E) is a primary expression whose type, value, and value category are identical to those of E . The parenthesized expression can be used in exactly the same contexts as those where E can be used, and with the same meaning, except as otherwise indicated [in C++14, C++17]


C++11: The operand of the the return statement can be either an expression or a braced-init-list.
A braced-init-list is not an expression; placing parentheses around it is a syntax error.
1
2
3
4
5
6
7
#include <vector>

std::vector<int> make_vec( int a, int b, int c, int d ) // C++11
{
    // return ( { a, b, c, d } ) ; // *** error: a braced-init-list is not an expression
    return { a, b, c, d } ; // fine: no parenthesis
}


If you are just beginning to learn C++, for now, you can safely ignore everything after this.


C++14: The placeholder type decltype(auto) behaves differently when the types are deduced from
a simple id-expression or from a parenthesised id-expression.
1
2
3
decltype(auto) foo() { static const int v = 0 ; return v ; } // return int (prvalue) // C++14

decltype(auto) bar() { static const int v = 0 ; return (v) ; } // return reference to const int // C++14(lvalue) 


C++17: The operand of the return statement can be a fold-expression.
A pair of parenthesis is an essential part of a fold-expression.
1
2
3
4
5
template < typename... T > auto plus( const T&... values ) // C++17
{
    // return ... + values  ; // *** error:  open and close parentheses are required parts of a fold expressions
    return ( ... + values ) ; // fine: return result of fold expression
}


Almost every core language feature added in C++11, C++14 and C++17 have made life a lot easier for people learning C++; however, by necessity, this has also introduced some edge-cases.
Last edited on
Topic archived. No new replies allowed.