hi

I remember there is some catch in doing this but what is it?Code:`if(a-b>0)`

... some casting I should do?

in what cases would it work and when not.

Printable View

- 07-16-2007kroizchecking for a posetive difference.
hi

Code:`if(a-b>0)`

... some casting I should do?

in what cases would it work and when not. - 07-16-2007Daved
Looks good to me as long as there is no overflow.

- 07-16-2007robatino
You could just write it as

Code:`if (a > b)`

- 07-16-2007kroiz
- 07-16-2007kroiz
- 07-16-2007kroiz
actually how do I do

Code:`if(x<0)`

- 07-16-2007robatino
There are only two possible issues with your expression that I can think of: first, if a and b are pointers into an array, then a-b is computed using a type called ptrdiff_t which is supposed to represent the integer difference between two pointers, but is not actually guaranteed to be able to hold the result. The other is that if a and b are unsigned integral types, then I think the difference is calculated as an unsigned type first and then compared to 0 (which is bad, since a-b would always be >= 0 regardless of a and b). I just tested this with gcc and this in fact happens, for example with a = 1 and b = 2, the test a-b > 0 passes. So my expression is safer for unsigned types - it should work properly in this case.

- 07-16-2007robatino
- 07-16-2007kroiz
but x should not be able to hold negative values.

Code:`unsigned int x=3;`

unsigned int y=4;

for(unsigned int i ; i< x-y ++i)

foo();

I would like something like this:

Code:`unsigned int x=3;`

unsigned int y=4;

int diff = x-y;

if(diff<0)

diff=0;

for(unsigned int i ; i<diff; ++i)

foo();

- 07-16-2007robatinoCode:
`for(unsigned int i ; i+y<x; ++i)`

- 07-16-2007kroiz
I see, I guess I can not avoid doing a comparison of who is bigger.

I just thought it is more readable to actually compare to zero. - 07-17-2007robatino
You could also use

Code:`unsigned int diff = (x > y)? x-y : 0;`

Code:`i < diff`

- 07-17-2007kroiz
Thanks robatino. (-:

- 07-17-2007Salem
> ptrdiff_t which is supposed to represent the integer difference between two pointers,

> but is not actually guaranteed to be able to hold the result.

Where did this come from? - 07-17-2007robatino
In the C standard,

http://c0x.coding-guidelines.com/6.5.6.html

see #1166. I'm assuming the C++ standard has the same behavior.