Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More concise way to write the following statement

Tags:

c++

Is there a more concise way to write the following C++ statements:

int max = 0;

int u = up();
if(u > max)
{
 max = u;
}

int d = down();
if(d > max)
{
max = d;
}

int r = right();
max = r > max ? r : max;  

Specifically is there a way to embed the assignment of the functions return inside the if statement/ternary operator?

like image 270
Alan Avatar asked Jul 26 '10 06:07

Alan


2 Answers

Assuming that:

  • The idea was to remove the local variables (i.e. you don't need u, d, r later on)
  • Evaluation order doesn't matter

... then you can just use std::max:

int m = max(max(max(0, up()), down()), right());

If this is the return value of the function:

return max(max(max(0, up()), down()), right());

Note that that can evaluate the functions in any order, rather than the string up, down, right order in your original code.

like image 187
Jon Skeet Avatar answered Oct 04 '22 03:10

Jon Skeet


#include <algorithm>
using namespace std;
...

int maxn = max(max(up(), down()), right());

If I'm not mistaken.

like image 23
Reinderien Avatar answered Oct 04 '22 04:10

Reinderien