Ryan Peschel
Ryan Peschel

Reputation: 11828

Way to simplify this array insertion code?

If I have this code:

array[0] = a < b ? c : d
array[1] = a < b ? d : c

Is there a way to simplify it elegantly?

I know I can do something like this to avoid the double boolean check:

if (a < b)
{
    array[0] = c;
    array[1] = d;
}
else
{
    array[0] = d;
    array[1] = c;
}

But it's rather verbose.

Am I missing something obvious?

Upvotes: 2

Views: 36

Answers (1)

mlorbetske
mlorbetske

Reputation: 5649

Compute the index to assign the variable to, instead of which variable to use for each index.

int cLocation = a < b ? 0 : 1;
array[cLocation] = c;
array[1 - cLocation] = d;

Upvotes: 5

Related Questions