I am trying to use 256 as a constant in C with #define. That equals 255 + 1 (which is 0xff + 1). And since in limits.h
, UCHAR_MAX
is 255, 256 should be equivalent to UCHAR_MAX
+ 1. So I write:
#include <limits.h>
#define BASE_NUM ((int)UCHAR_MAX)+1
So, when I do printf("%f",1000.0/(float)BASE_NUM);
, it prints 4.921569, which is wrong (it would only be correct if BASE_NUM
was 203.187).
However, by writing printf("%f",1000.0/((float)UCHAR_MAX+1));
, I get 3.906250 as the output, and it is indeed correct. Therefore, BASE_NUM
must not be equal to 256, but astonishingly, printf("%d",BASE_NUM);
prints 256, which is clearly a contradiction, as BASE_NUM
must not actually be 256.
I guess it has something to do with an overflow when I do the sum at the definition of the constant, but I really can't see what the problem exactly is, given that I am casting UCHAR_MAX
to an int before adding anything to it, so there should be no overflow.