Assigning a reference with if statements?

Viewed 124

In C++, we can assign a reference using the conditional operator as such:

int main (int argc, char *argv[])
{
    int i, j;
    int &k = (false) ? i : j;
}

Is it possible to do this with if-else statements? I don't see how you can do it because you can't reassign a reference.

2 Answers

Sure, but you probably don't want to.

int main(int argc, char *argv[])
{
    int i, j;
    bool cond = false;
    int &k = [&]() -> int& { if (cond) return i; else return j; }();
}

Or, if you're allergic to stupid lambda tricks:

int& pickARef(bool cond, int& trueRef, int& falseRef)
{
    if (cond)
    {
        return trueRef;
    }
    else
    {
        return falseRef;
    }
}


int main(int argc, char *argv[])
{
    int i, j;
    bool cond = false;
    int &k = pickARef(cond, i, j);
}

Neither one looks like a good idea to me.

Not ideal, but you can use std::reference_wrapper when you need a re-assignable reference, eg:

#include <functional>

int main (int argc, char *argv[])
{
    int i, j;
    std::reference_wrapper<int> k;
    if (condition)
        k = i;
    else
        k = j;
    // use k/k.get() as needed
}

Though, in this case, I would just use a pointer instead:

int main (int argc, char *argv[])
{
    int i, j;
    int *k;
    if (condition)
        k = &i;
    else
        k = &j;
    // use *k as needed
}
Related