简体   繁体   中英

C++ “return” the result of an expression

Is there any difference between the evaluation of expressions between the two return statements below, based on the extra parenthesis?

    return a++ *(-b+123.456)/999.12344;

vs

    return (a++ *(-b+123.456)/999.12344);

Programming Language C++ Standards CPP 98'ish (Before C++11)

Hope the question is clear. Expectation is to evaluate the expression in full.

Sloppy speaking x is the same as (x) (see this answer for the "striclty speaking" answer ;). Adding parentheses around the full expression does not change anything about operator precedence .

PS: It has an obscure impact on return value optimization (see this answer for the details). Though, it definitely has no impact on the value that is returned.

There are differences. Using parentheses will obviate return value optimisation .

If, for example, a and / or b were objects with all suitable operators overloaded, then using parentheses could suffer you the overhead of an object value copy.

For plain-old-data there is no difference, subject to the C++11 abomination

decltype(auto) ub_server() { int a; return (a);}

which actually gives you a dangling reference .

In summary: Don't use the enclosing parentheses unless you want some of the above behaviour, and possibly only then with a supporting comment.

Is there any difference between the evaluation of expressions between the two return statements below, based on the extra parenthesis?

No; the parentheses are completely redundant in this case .


An expression expr is actually not the same as an expression (expr) , and you can observe this with return because copy/move elision is inhibited in the latter case:

#include <iostream>

struct T
{
    T() { std::cout << "T()\n"; }
    T(const T&) { std::cout << "T(const T&)\n"; }
    T(T&&) { std::cout << "T(T&&)\n"; }
    ~T() { std::cout << "~T()\n"; }
};

T foo()
{
    T t;
    return t;
}

T bar()
{
    T t;
    return (t);
}

int main()
{
    std::cout << "Test 1\n------\n";
    foo();
    std::cout << '\n';
    std::cout << "Test 2\n------\n";
    bar();
}

Output:

Test 1
------
T()
~T()

Test 2
------
T()
T(T&&)
~T()
~T()

( live demo )

You can probably observe the same result before C++17 because compilers have always tried to optimise return values. Even in your standard, C++98, you can probably observe that the copy constructor isn't invoked in the first case.

But, hey, none of that is relevant for a simple arithmetic expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM