lwip-devel
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [lwip-devel] LWIP_U32_DIFF is unnecessarily complex


From: David Brown
Subject: Re: [lwip-devel] LWIP_U32_DIFF is unnecessarily complex
Date: Thu, 24 Nov 2011 09:12:36 +0100
User-agent: Mozilla/5.0 (Windows NT 5.1; rv:8.0) Gecko/20111105 Thunderbird/8.0

On 23/11/2011 20:23, Mike Kleshov wrote:
On 23 November 2011 17:37, David Brown<address@hidden>  wrote:
Since unsigned addition cannot overflow, nor can unsigned subtraction.

It makes sense. I only wanted to see the exact quote from the standard
to clearly support this. It appears there is none. Although, the
intent of the standard appears to be: subtraction of unsigned integers
is as well-behaved as addition.


One day, I'll get a copy of the current standards so that I can quote appropriately...

Since unsigned addition cannot overflow, nor can unsigned subtraction. So
the macro LWIP_U32_DIFF should be defined simply:

#define LWIP_U32_DIFF(a, b) ((a) - (b))

assuming the comment "'a' is expected to be higher than 'b'" is valid.

If that comment is not valid, a better definition would be:

#define LWIP_U32_DIFF(a, b) (((a)>= (b)) ? ((a) - (b)) : ((b) - (a)))

This last define is so wrong. You seem to misunderstand the phrase
"'a' is expected to be higher than 'b'". It assumes that a and b are
snapshots of a free-running 32-bit timer, so 'a' would be later than
'b'. They can easily be (a>  b) or (a<  b) in unsigned arithmetic
sense.


In that case, I think the comment is wrong - an easily misinterpreted comment is worse than no comment. And the name of the macro is also wrong, since it is only targeted at specific circumstances rather than being a general "difference" macro.

When you know that a is "higher" than b, in the sense used here, then the difference is just (a - b) in unsigned arithmetic.

If you don't know which is "higher", it is safer (i.e., easier to get the code correct) to use signed integers. But the only place I found in lwip that uses LWIP_U32_DIFF is, as you say, when comparing snapshots of a 32-bit timer.






reply via email to

[Prev in Thread] Current Thread [Next in Thread]