(PJ/Mark/some moderator: the parent comment is breaking the layout of the
page somehow, could you edit it to fix that? It's probably an unbalanced
tag.) I had a different reaction to the question. If I'm writing an "add"
function in my compiler, it's probably because I need to implement addition in
terms of simpler operations because it doesn't exist on the platform I'm aiming
for. The only reasonable interpretation of that would be if I'm trying to add
numbers too wide for the compiler to handle natively, so I'd do something like
this (note: this code is machine-specific, to a little-endian system which has
32-bit ints and two's complement signed overflow but cannot natively add more
than 16 bits, again as you'd expect for a task like
this): int add(int i, int j)
{
unsigned
short i_low = ((short*)&i)[0];
short i_high =
((short*)&i)[1];
unsigned short j_low =
((short*)&j)[0];
short j_high =
((short*)&j)[1];
unsigned short r_low = i_low +
j_low;
short r_high = i_high + j_high;
int
r;
/* handle carry: if i_low + j_low overflows, the
result
will be less than some input, otherwise
it will be
greater than or equal to both
inputs */
if (i_low + j_low < i_low
||
i_low + j_low < j_low)
r_high++;
((short*)&r)[0] =
r_low;
((short*)&r)[1] = r_high;
return
r;
} This was written from memory (and may wel contain
mistakes), but I believe there's some pretty similar code in gcc somewhere,
again trying to implement the addition operator as a function. In general,
writing a function to do addition is a little pointless unless the
implementation is a complicated one like this; you'd just use the operator
instead. Also, even if you did need to write something like this out, it'd be
better to get at the carry flag in some system-specific way rather than doing
extra arithmetic. [ Reply to This | Parent | # ]
|