Search code examples
c++referencereturnconditional-operatorassignment-operator

Can I assign and return without a utility routine?


Is there a way to "assign and return" without creating a utility routine? Here's my code:

static int& do_work_(const int* p, int& result)
{
   result = (*p) * 10;
   return result;
}

template<typename T>
T& assign(const T* p, T& result)
{
   result = *p;
   return result;
}

int& do_work(const int* p, bool cond, int& result)
{
   return cond ? do_work_(p, result) : assign(p, result);
}

Can I implement do_work() without the assign() utility?


The reason for the do_work() signature is that it's a nice convenience:

const int value=1;
int i, j;
if (do_work(&value, true, i) == do_work(&value, false, j)) {}

Solution

  • If you want to return the result of an assignment operation you can (in most cases) do so without a 'utility' function like your assign, because the assignment expression itself has a value; from cppreference (bolding mine):

    The direct assignment operator expects a modifiable lvalue as its left operand and an rvalue expression or a braced-init-list (since C++11) as its right operand, and returns an lvalue identifying the left operand after modification.

    Or, from this Draft C++17 Standard:

    8.5.18 Assignment and compound assignment operators       [expr.ass]

    1   The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand; their result is an lvalue referring to the left operand. …

    Thus, as suggested in the comments, you can simply have the following:

    int& do_work(const int* p, bool cond, int& result)
    {
       return cond ? do_work_(p, result) : (result = *p);
    }