F
Frederick Gotham
Eric Sosman:
Just to make sure I understand here... What that line does is equivalent
to:
unsigned const one_unsigned = 1;
long unsigned x = -one_unsigned;
In order to compute "-one_unsigned", we must traipse over to omnipotent
maths world. In omnipotent maths world, we calculate that the negative of 1
is -1. We then try to store -1 in an unsigned int. Therefore, we can expand
the code to:
unsigned const one_unsigned = 1;
unsigned const negative_of_one_unsigned = -one_unsigned;
long unsigned x = negative_of_one_unsigned;
And of course, this is equal to:
long unsigned x = UINT_MAX;
What the person _should_ have written is:
long unsigned x = ULONG_MAX;
or:
long unsigned x = -1;
Or, if the objective was to set all bits (including padding bits) to 1:
long unsigned x;
memset(&x,UCHAR_MAX,sizeof x);
Anyhow... this just goes to show how I'd never have a use for negating an
unsigned integer.
I once spent
time chasing a bug whose root cause was (paraphrased)
unsigned long x = -1u;
... as a shorthand for "Fill `x' with 1-bits."
Just to make sure I understand here... What that line does is equivalent
to:
unsigned const one_unsigned = 1;
long unsigned x = -one_unsigned;
In order to compute "-one_unsigned", we must traipse over to omnipotent
maths world. In omnipotent maths world, we calculate that the negative of 1
is -1. We then try to store -1 in an unsigned int. Therefore, we can expand
the code to:
unsigned const one_unsigned = 1;
unsigned const negative_of_one_unsigned = -one_unsigned;
long unsigned x = negative_of_one_unsigned;
And of course, this is equal to:
long unsigned x = UINT_MAX;
What the person _should_ have written is:
long unsigned x = ULONG_MAX;
or:
long unsigned x = -1;
Or, if the objective was to set all bits (including padding bits) to 1:
long unsigned x;
memset(&x,UCHAR_MAX,sizeof x);
Anyhow... this just goes to show how I'd never have a use for negating an
unsigned integer.