N
Noob
Hello,
I've come across the following macro:
/** Get the absolute difference between 2 u32_t values (correcting overflows)
* 'a' is expected to be 'higher' (without overflow) than 'b'. */
#define FOO_U32_DIFF(a, b) (((a) >= (b)) ? ((a) - (b)) : (((a) + ((b) ^ 0xFFFFFFFF) + 1)))
(u32_t is equivalent to uint32_t)
In my opinion, the entire macro reduces to ((a)-(b)) since
((b) ^ 0xFFFFFFFF) + 1 is always equal to -b (since uint32_t
arithmetic is carried out modulo 2^32).
Do you agree that the macro can be simplified, with no loss
in portability whatsoever?
I wrote a small program to try to illustrate my point.
#include <stdio.h>
int main(void)
{
volatile unsigned b = 0;
do
{
unsigned v1 = (b ^ 0xFFFFFFFF) + 1;
unsigned v2 = -b;
if (v1 != v2) printf("b=%u v1=%u v2=%u\n", b, v1, v2);
}
while (++b != 0);
return 0;
}
My compiler generates the same instruction to compute
v1 and v2.
Regards.
I've come across the following macro:
/** Get the absolute difference between 2 u32_t values (correcting overflows)
* 'a' is expected to be 'higher' (without overflow) than 'b'. */
#define FOO_U32_DIFF(a, b) (((a) >= (b)) ? ((a) - (b)) : (((a) + ((b) ^ 0xFFFFFFFF) + 1)))
(u32_t is equivalent to uint32_t)
In my opinion, the entire macro reduces to ((a)-(b)) since
((b) ^ 0xFFFFFFFF) + 1 is always equal to -b (since uint32_t
arithmetic is carried out modulo 2^32).
Do you agree that the macro can be simplified, with no loss
in portability whatsoever?
I wrote a small program to try to illustrate my point.
#include <stdio.h>
int main(void)
{
volatile unsigned b = 0;
do
{
unsigned v1 = (b ^ 0xFFFFFFFF) + 1;
unsigned v2 = -b;
if (v1 != v2) printf("b=%u v1=%u v2=%u\n", b, v1, v2);
}
while (++b != 0);
return 0;
}
My compiler generates the same instruction to compute
v1 and v2.
Regards.