hi
i have a problem with integer subtraction in C.
printf("%d", c < (a - b));
a is got from a #define and is 0x80000000 and b is got from input and
is also 0x80000000.
c is ffffffff (-1).
Now, this should print 1 (true) but it prints 0!
Are you _sure_ that an int can hold such values?
The following code should produce, on most implementations, a number of
warnings. Pay attention to the warnings, and then think about what they
and the possibly strange-looking output might mean:
#include <stdio.h>
int main(void)
{
unsigned short usc = 0xffffffff, usa = 0x80000000, usb = 0x80000000;
/* the above line leads to truncation in my implementation, shorts
not being 32 bits */
unsigned long ulc = 0xffffffffL, ula = 0x80000000L, ulb =
0x80000000L;
signed short ssc = 0xffffffff, ssa = 0x80000000, ssb = 0x80000000;
/* the above line leads to truncation in my implementation, shorts
not being 32 bits */
signed long slc = 0xffffffffL, sla = 0x80000000L, slb = 0x80000000L;
printf("[Output for this implementation]\n");
printf("%d < (%d - %d)? %s\n",
ssc, ssa, ssb, (ssc < (ssa - ssb)) ? "yes" : "no");
printf("%ld < (%ld - %ld)? %s\n",
slc, sla, slb, (slc < (sla - slb)) ? "yes" : "no");
printf("%u < (%u - %u) or %x < (%x - %x)? %s\n",
usc, usa, usb,
usc, usa, usb, (usc < (usa - usb)) ? "yes" : "no");
printf("%lu < (%lu - %lu) or %lx < (%lx - %lx)? %s\n\n",
ulc, ula, ulb,
ulc, ula, ulb, (ulc < (ula - ulb)) ? "yes" : "no");
usc = 0xffff;
usa = 0x8000;
usb = 0x8000;
ulc = 0xffffL;
ula = 0x8000L;
ulb = 0x8000L;
ssc = 0xffff;
ssa = 0x8000;
ssb = 0x8000;
/* the above lines lead to truncation in my implementation, shorts
not being 32 bits */
slc = 0xffffL;
sla = 0x8000L;
slb = 0x8000L;
printf("%d < (%d - %d)? %s\n",
ssc, ssa, ssb, (ssc < (ssa - ssb)) ? "yes" : "no");
printf("%ld < (%ld - %ld)? %s\n",
slc, sla, slb, (slc < (sla - slb)) ? "yes" : "no");
printf("%u < (%u - %u) or %x < (%x - %x)? %s\n",
usc, usa, usb,
usc, usa, usb, (usc < (usa - usb)) ? "yes" : "no");
printf("%lu < (%lu - %lu) or %lx < (%lx - %lx)? %s\n\n",
ulc, ula, ulb,
ulc, ula, ulb, (ulc < (ula - ulb)) ? "yes" : "no");
return 0;
}
[Output for this implementation]
-1 < (0 - 0)? yes
-1 < (-2147483648 - -2147483648)? yes
65535 < (0 - 0) or ffff < (0 - 0)? no
4294967295 < (2147483648 - 2147483648) or ffffffff < (80000000 -
80000000)? no
-1 < (-32768 - -32768)? yes
65535 < (32768 - 32768)? no
65535 < (32768 - 32768) or ffff < (8000 - 8000)? no
65535 < (32768 - 32768) or ffff < (8000 - 8000)? no