comma operator causes hard to spot bugs

Artur Skawina art.08.09 at gmail.com
Sat Apr 21 05:49:06 PDT 2012


On 04/21/12 14:23, Benjamin Thaut wrote:
> Hi,
> I just had a bug due to the unitentional usage of the comma operator. So I'm wondering if there could something be done so that the compiler prevents something like this:
> 
> memStart = cast(T*)(m_allocator.AllocateMemory(size * T.sizeof), InitializeMemoryWith.NOTHING);
> 
> This first excutes AllocateMemory, then throws away the result and then casts the enum InitializeMemory.NOTHING value to a pointer, which will always result in a null pointer. This took me quite some time to spot.
> What I actually wanted to do:
> 
> memStart = cast(T*)(m_allocator.AllocateMemory(size * T.sizeof, InitializeMemoryWith.NOTHING));
> 
> 1) So is it actually neccessary that enums can be casted directly to pointers?
> 2) Is the functionality provided by the comma operator actually worth the bugs it causes?

Probably, but it *is* rarely used...

However the problem is the allocator, which should also take the type is an
argument and do the cast internally. That plus an overload for arrays would avoid
these kinds of bugs (since an API like this will be enough for most use cases).
And, yes, the D std runtime got this wrong too.
(The void*alloc(size_t,flags) versions are useful sometimes, of course)

artur


More information about the Digitalmars-d mailing list