auto init & what the code means

spir denis.spir at gmail.com
Sun Dec 26 05:33:22 PST 2010


Hello,

I have a problem with D's auto-init feature. When reading in someone else's code
	int i;
there is no way, I guess, to know whether this means "i is initialised to 0" or "i is left undefined". For this reason, in the former case I do explicitely initialise. Thus,
	int i = 0;	// means initialised
	int i;		// means undefined _for me_
But, as _for me_ emphasizes, another reader still cannot guess the latter case.

I would enjoy having an idiom to express this clearly. Without it, a possibility may be to use a conventional comment like
	int i;	// undef
in public code (esp Phobos) and spread the word about it. (Then, variable declarations without init or comment are known to be by people who do not use this convention, and we know we need to search farther in code to interpret them.)

Note that this problem does not apply to floats or pointers/refs, for which .init is invalid for operating anyway. But there is a weird ambiguity about null/uninitialised arrays & strings which behave like empty in most cases. I would enjoy this to be clarified as well. For instance:
	int[] ints1 = [];
	ints1 ~= 1;		// ok
	int[] ints2;
	ints2 ~= 1;		// error
So that arrays behave like pointed/ref'ed thingies. (But I'm unsure about the best way.) (*)

Denis

(*) This is also related to the boolean / null-compare value os arrays and strings:
void main()
{
    writeln("array -- undef");
    int[] ints1;
    writeln('(',ints1,')');
    if (ints1) writeln("ints1");
    if (ints1 != null) writeln("ints1");
    if (ints1 !is null) writeln("ints1");
    ints1 ~= 1;
    writeln('(',ints1,')');
    
    writeln("array -- def");
    int[] ints2 = [];
    writeln('(',ints2,')');
    if (ints2) writeln("ints2");
    if (ints2 != null) writeln("ints2");
    if (ints2 !is null) writeln("ints2");
    ints2 ~= 1;
    writeln('(',ints2,')');
    
    writeln("string -- undef");
    string str1;
    writeln('(',str1,')');
    if (str1) writeln("str1");
    if (str1 != null) writeln("str1");
    if (str1 !is null) writeln("str1");
    str1 ~= '1';
    writeln('(',str1,')');
    
    writeln("string -- def");
    string str2 = "";
    writeln('(',str2,')');
    if (str2) writeln("str2");
    if (str2 != null) writeln("str2");
    if (str2 !is null) writeln("str2");
    str2 ~= '1';
    writeln('(',str2,')');
}  
==>
array -- undef
()
([1])
array -- def
()
([1])
string -- undef
()
(1)
string -- def
()
str2
str2
(1)
-- -- -- -- -- -- --
vit esse estrany ☣

spir.wikidot.com



More information about the Digitalmars-d mailing list