Can someone explain to me how come these two operations yield different return values, using x=200, y=100?
Code:// this returns 200
((x + y) > 255) ? (255) : (x + y);
// this returns 255
if((x + y) > 255) return 255;
return x + y;
Printable View
Can someone explain to me how come these two operations yield different return values, using x=200, y=100?
Code:// this returns 200
((x + y) > 255) ? (255) : (x + y);
// this returns 255
if((x + y) > 255) return 255;
return x + y;
It doesn't. It works fine. Your problem is elsewhere.
For starters, the ternary operator can't return 200. It'll return either 255 or 300.
The output of this program is 255, so it appears that you are mistaken:
Code:#include <stdio.h>
int foo(int x, int y)
{
return ((x + y) > 255) ? (255) : (x + y);
}
int main(void)
{
printf("%d\n", foo(200, 100));
return 0;
}
Well, given that the above line of code doesn't actually include the word "return" in it, I wouldn't be surprised by ANY particular value it happened to return. In fact, I'm particularly unsurprised that it returns 200, because the value is probably loaded into a register during the (pointless) comparisons and additions, then just happens to be sitting there when you return from the function without actually returning anything. I bet if you turn on optimization the value will change.
EDIT: Also, you guys are assuming the types are int, and there's no reason to assume that. If they were char, the datatype which actually makes the most sense here, the code would return 44. This is not the correct way to do a saturation!
EDIT EDIT: The correct way is this:
Code:return ( 255 - x < y ) ? 255 : ( x + y );
I should have mentioned the return value is actually a char not int, it should still return 255 though right?
OK I see, thanks a lot for your help.
I did not assume int: I merely provided an example that uses int. Without knowing the context of "Saturation Arithmetic", I think int makes more sense than char, though unsigned char might make nearly as much sense as int.Quote:
Originally Posted by brewbuck
Or have an implementation defined result, if char is signed and CHAR_MAX is less than 300.Quote:
Originally Posted by brewbuck
Normally, what is meant is clamping to the minimum/maximum values of the data type instead of allowing it to overflow.
True, but in any case the result isn't right.Quote:
Or have an implementation defined result, if char is signed and CHAR_MAX is less than 300.