No segfault -> null == ""

Unknown W. Brackets unknown at simplemachines.org
Tue Mar 31 07:35:08 PDT 2009


Please remember, strings are not objects.

Therefore, a comparison against null does not cause a segfault, as it 
might with an object.  In the case of arrays, "test == null" and "test 
is null" should be the same operation.

In contrast, if you had null == new Object(), you would've seen:

name.d(6): Error: use 'is' instead of '==' when comparing with null

-[Unknown]


Qian Xu wrote:
> Hi All,
> 
> When I was trying to learn how char-array works, I found something
> unexpected.
> 
> -------------------------- code ------------------------------
> module string_test;
> 
> void main()
> {
>   // test 1
>   assert(null == "", "null is empty"); // No segfault
> 
>   // test 2
>   char[] test; // test = null;
>   assert(test is null, "undefined_string is null");
>   assert(test == "", "undefined_string (null) is empty");
>   assert(test.length == 0, "undefined_string.length == 0");
> 
>   // test 3
>   test = "";
>   assert(test !is null, "empty_string is NOT null");
>   assert(test == "", "empty_string is empty");
>   assert(test.length == 0, "empty_string.length == 0");
> 
>   // test 4
>   test = "hello";
>   assert(test !is null, "non_empty_string is NOT empty");
>   assert(test != "", "non_empty_string is NOT empty");
>   assert(test.length > 0, "non_empty_string.length > 0");
> }
> -------------------------- code ------------------------------
> 
> I just wondered, why the first test does not lead to a segfault. Is this an
> undocumented compiler feature? I have tested it with gdc and gdmd. Both no
> segfault.
> 
> 
> --Qian


More information about the Digitalmars-d-learn mailing list