Take this example program:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int
main(void)
{
uint32_t n = arc4random();
printf("arc4random %d\n", n);
printf("abs %d\n", abs(n));
return 0;
}
It gives the following warning when compiling:
test.c:11:21: warning: taking the absolute value of unsigned type
'uint32_t' (aka 'unsigned int') has no effect [-Wabsolute-value]
printf("abs %d\n", abs(n));
^
test.c:11:21: note: remove the call to 'abs' since unsigned values
cannot be negative
printf("abs %d\n", abs(n));
^~~
Which is well and good. However, I get the following output.
laptop$ ./a.out
arc4random 247165650
abs 247165650
laptop$ ./a.out
arc4random 2012715611
abs 2012715611
laptop$ ./a.out
arc4random 222644175
abs 222644175
laptop$ ./a.out
arc4random -843593186
abs 843593186
So on the fourth try I got what appears to be a negative number back.
I'm not sure if this is some printf() funny business or what. Please
explain. In real life I don't intend on using this with printf() so If
thats the case no worries. However, if not I need to know that my random
number is positive. I also tried if (n < 0) etc.. and got similar warnings.
Thanks in advance,
Edgar