Shortest way to calculate difference between two numbers?

#include <cstdlib>

int main()
{
    int x = 7;
    int y = 3;
    int diff = std::abs(x-y);
}

Using the std::abs() function is one clear way to do this, as others here have suggested.

But perhaps you are interested in succinctly writing this function without library calls.

In that case

diff = x > y ? x - y : y - x;

is a short way.

In your comments, you suggested that you are interested in speed. In that case, you may be interested in ways of performing this operation that do not require branching. This link describes some.


Just get the absolute value of the difference:

#include <cstdlib>
int diff = std::abs(x-y);

Tags:

C++

Math