DMD can implicitly convert class pointer to the bool. Is it bug or terrible feature?

Maxim Fomin maxim at maxim-fomin.ru
Sun Nov 24 06:28:39 PST 2013


On Sunday, 24 November 2013 at 14:18:50 UTC, ilya-stromberg wrote:
> On Sunday, 24 November 2013 at 14:12:18 UTC, Maxim Fomin wrote:
>> void* ptr;
>> if(ptr)
>>
>> was a shortcut for 'if(ptr != NULL)' probably since C was 
>> created.
>
> Small code change:
>
> import std.stdio;
>
> class Foo
> {
> }
>
> void main()
> {
> 	Foo f;
> 	
> 	if(f == null)
> 	{
> 		writeln("f is true");
> 	}
> 	
> 	if(f != null)
> 	{
> 		writeln("f is false");
> 	}
> }
>
> DMD output:
>
> Error: use 'is' instead of '==' when comparing with null
> Error: use '!is' instead of '!=' when comparing with null
>
> So, C style 'if(ptr != NULL)' isn't allowed in D.

Yes, because D is separate language, and its comparison operator 
does something special when operands are class references. This 
is not the same story as in 'if(f)' which is purely bitwise 
comparison.

I think your question is more appropriate for d.learn.


More information about the Digitalmars-d mailing list