I'd write something like this:
int max = 0;
maximize(max, up());
maximize(max, down());
maximize(max, right());
Where maximize
takes the first variable by reference, and a second variable as an offering. If the offering is greater than the first variable, then the first variable is set to the offering.
void maximize(int& v, int offering) {
if (offering > v) {
v = offering;
}
// or use std::max
}
Benefits
The other alternative to maximize
is this one-liner nested-max
expression:
// nested-max alternative; more "functional" style
int v = max(max(max(defaultValue, val1), val2), val3);
Contrast this with the multi-step refinement maximization process:
// multi-step maximize alternative; more "imperative" style
int v = defaultValue;
maximize(v, val1);
maximize(v, val2);
// perhaps do something else in between...
maximize(v, val3);
Though not as concise, this latter approach offers the following:
- A linearized form can be more readable than a deeply nested
max
expression
- You can do something in between each maximization steps if you need to
- The order of the maximization steps are explicit
- It's also easily to reorder by moving individual statements around
On assignment in condition
And now we address the following part of the question:
Specifically is there a way to embed the assignment of the functions return inside the if statement/ternary operator?
If you insist on doing something like this, you can always use a temporary variable as follows:
int offer;
if ((offer=up()) > max) {
max = offer;
}
if ((offer=down()) > max) {
max = offer;
}
max = ((offer=right()) > max) ? offer : max;
This does not result in a very readable code in this case, but there are idiomatic ways to use an assignment in a condition in some scenarios.
Related questions