Growing a Language (applicable to @attribute design)
Joseph Rushton Wakeling
joseph.wakeling at webdrake.net
Thu Nov 15 13:08:12 PST 2012
On 11/15/2012 11:54 AM, Walter Bright wrote:
> size_t x = 1;
Complete misunderstanding there -- I'd interpreted Simen's remark as saying that
e.g. auto x = 1; would automatically assign the correct type where builtins were
concerned, and I was pointing out that this wouldn't cover all builtins. Though
I guess auto x = 1UL; would work.
I wasn't asking how to create a size_t per se, which I do know how to do ... :-)
I once came an awful cropper due to lack of UL in an integer assignment. I'd
got a bit of C(++) code like this:
size_t p = 1 << m;
where m was chosen such that p would be the largest power of 2 on the system
that could (i) be multiplied by 2 without integer wraparound and (ii) was within
the range of the uniform integer random number generator in use.
And that worked fine ... until I installed a 64-bit OS, and suddenly, all the
numbers were coming out different.
They shouldn't have been, because the RNG in use was still based around int32_t
and so the same constraints on m and p should have been in place ... and then I
discovered what was happening: 1 << m; wasn't taking a size_t (unsigned long)
and bitshifting it by m places, it was taking a regular int and bitshifting it
by m places ... which given the value of m, was causing integer wraparound, the
result of which was then converted to a size_t.
It just so happened that on 32-bit this was taking the value back to where it
was supposed to be anyway. But on 64-bit the wraparound made 1 << m a negative
number which in turn corresponded to a far too _large_ value when converted into
a size_t.
And so I learned that I had to use 1UL << m; instead ... :-P
More information about the Digitalmars-d
mailing list