Here's a C version riffing off of the solution in the question post, but fixes the case where all of the values are MaxInt...
int foo(int value1, int value2, int value3)
{
int value1Temp, value2Temp, value3Temp, tempMax;
value1Temp = max(value1, 0);
value2Temp = max(value2, 0);
value3Temp = max(value3, 0);
tempMax = value1Temp | value2Temp | value3Temp;
if (value1Temp == 0) { value1Temp = tempMax; }
if (value2Temp == 0) { value2Temp = tempMax; }
if (value3Temp == 0) { value3Temp = tempMax; }
return min(value1Temp, min(value2Temp, value3Temp));
}
It's also possible to do this in a branch-free way, since min and max can be implemented as branch-free operations:
int min(int x, int y)
{
return y + ((x - y) & -(x < y));
}
int max(int x, int y)
{
return x - ((x - y) & -(x < y));
}
int foo(int value1, int value2, int value3)
{
int value1Temp, value2Temp, value3Temp, tempMax, mask;
value1Temp = max(value1, 0);
value2Temp = max(value2, 0);
value3Temp = max(value3, 0);
tempMax = value1Temp | value2Temp | value3Temp;
mask = -(value1Temp > 0);
value1Temp = (value1Temp & mask) | (tempMax & ~mask);
mask = -(value2Temp > 0);
value2Temp = (value2Temp & mask) | (tempMax & ~mask);
mask = -(value3Temp > 0);
value3Temp = (value3Temp & mask) | (tempMax & ~mask);
return min(value1Temp, min(value2Temp, value3Temp));
}
For more background on why you'd ever want to do this, see: Is "If" Expensive? and Bit Twiddling Hacks.
Edit: Clobbered my earlier attempt at a branch-free solution, which didn't actually work. Added a new branch-free solution which should work.