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
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.
Looks good to me as long as there is no overflow.
You could just write it as
Code:if (a > b)
actually how do I do
if x is unsigned.Code:if(x<0)
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.
but x should not be able to hold negative values.
see the problem here? I would like the loop to run zero times.Code:unsigned int x=3;
unsigned int y=4;
for(unsigned int i ; i< x-y ++i)
foo();
I would like something like this:
another problem is that diff in the above example might not be big enough to hold the difference between x and y, since it signed and thus half the size.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();
Now both sides of the comparison are >=0 and it works. (BTW, you need to initialize i, I didn't since I don't know what value you want.)Code:for(unsigned int i ; i+y<x; ++i)
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.
You could also use
and thenCode:unsigned int diff = (x > y)? x-y : 0;
which would be a little more efficient since you're not doing the addition each time through the loop.Code:i < diff
Thanks robatino. (-:
> 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?
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.