It is a bit uglier than Alan's trick, but it cannot cause overflow, nor numerical errors, and so on:
int x, y, z, median;
...
if (x <= y && y <= z || y >= z && y <= x) median = y;
else if (y <= x && x <= z || x >= z && x <= y) median = x;
else median = z;
The algorithm is simply this:
check if x is between y and z, if yes, that is it.
check if y is between x and z, if yes, that is it.
It must be z since it was neither x, nor y.
=====================================================
You could also get this more flexibly if you have more than three elements, with sorting.
// or xor implementation, does not matter...
void myswap(int* a, int* b)
{
int temp = *b;
*b = *a;
*a = temp;
}
int x, y, z;
// Initialize them
int min = x;
int med = y;
int max = z;
// you could also use std::swap here if it does not have to be C compatible
// In that case, you could just pass the variables without the address operator.
if (min > med) myswap(&min, &med);
if (med > max) myswap(&med, &max);
if (min > med) myswap(&min, &med);