# How to code "if calculation returns a negative value, result = 0"

Hi forum,

I am having trouble thinking through this simple problem, I am subtracting 2 variables, both have a range of 0 to 15 and I was using the constrain function to keep the result of the calculation between 0 and 15 (intending to code - if the subtraction results in a negative value then return 0) ie:

``````byte result = x - y;
result = constrain(result, 0, 15);
``````

But in this code, if the result of the subtraction is a negative value I get the upper end of the constrain function (15) as the output where I thought I would get 0.

How would I code this argument correctly?

problem with byte is that if you subtract 10 from 5, you don't get -5, because bytes can't represent -5, they can only do 0 - 255, and if you go over the limit, it wraps around, so 5 - 10 = 250 (give or take one)
I would suggest the following code:

``````if (y > x) {
result = 0;
} else {
result = x -y;
}
``````

or, if you want to simplify it, you could use the ? : expression:

``````result = (y > x) ? 0 : x-y;
[code]
``````

[/code]

The problem is that the byte data type

It does not hold negative numbers

Use the int data type

Do you actually know that x is supposed to be the larger number ?

If you just want to know the difference between them, and you don't make the assumption that a specific one is the bigger one, I'd write

``````result = abs ( x - y );
``````

Thanks to everyone for the replies, all nice tips.

TRex:
problem with byte is that if you subtract 10 from 5, you don't get -5, because bytes can't represent -5, they can only do 0 - 255, and if you go over the limit, it wraps around, so 5 - 10 = 250 (give or take one)
I would suggest the following code:

``````if (y > x) {
``````

result = 0;
} else {
result = x -y;
}

``````

or, if you want to simplify it, you could use the ? : expression:

``````

result = (y > x) ? 0 : x-y;

[code]

``````
[/code]
``````

Thank you very much T-Rex, this is the perfect solution for this application. I didn't realise that byte loops back around to 255 when you pass 0 and that was causing the confusion so this ensures that I get 0 if the result is negative.

Thanks again!