The Nullity Of strings and Its Meaning
kdevel via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Jul 8 10:16:51 PDT 2017
Yesterday I noticed that std.uri.decodeComponent does not
'preserve' the
nullity of its argument:
1 void main ()
2 {
3 import std.uri;
4 string s = null;
5 assert (s is null);
6 assert (s.decodeComponent);
7 }
The assertion in line 6 fails. This failure gave rise to a more
general
investigation on strings. After some research I found that one
"cannot implicitly convert expression (s) of type string to bool"
as in
1 void main ()
2 {
3 string s;
4 bool b = s;
5 }
Nonetheless in certain boolean contexts strings convert to bool
as here:
1 void main ()
2 {
3 import std.stdio;
4 string s; // equivalent to s = null
5 writeln (s ? true : false);
6 s = "";
7 writeln (s ? true : false);
8 }
The code prints
false
true
to the console. This lead me to the insight, that in D there are
two
distinct kinds of empty strings: Those having a ptr which is null
and
the other. It seems that this ptr nullity not only determines
whether
the string compares equal to null in an IdentityExpression [1]
but also
the result of the above mentioned conversion in the boolean
context.
I wonder if this distinction is meaningful and---if not---why it
is
exposed to the application programmer so prominently.
Then today I found this piece of code
1 void main ()
2 {
3 string s = null;
4 string t = "";
5 assert (s is t);
6 }
which, according to the wording in [1]
"For static and dynamic arrays, identity is defined as
referring to
the same array elements and the same number of elements."
shall succeed but its assertion fails [2]. I anticipate the
implementation compares the ptrs even in the case of zero
elements.
A last example of 'deviant behavior' I found is this:
1 import std.stdio;
2 import std.file;
3 void main ()
4 {
5 string s = null;
6 try
7 mkdir (s);
8 catch (Exception e)
9 e.msg.writeln;
10
11 s = "";
12 try
13 mkdir (s);
14 catch (Exception e)
15 e.msg.writeln;
16 }
Using DMD v2.073.2 the first expression terminates the programm
with a
segmentation fault. With 2.074.1 the program prints
: Bad address
: No such file or directory
I find that a bit confusing.
[1] https://dlang.org/spec/expression.html#identity_expressions
[2] https://issues.dlang.org/show_bug.cgi?id=17623
More information about the Digitalmars-d-learn
mailing list