October 01, 2002 zero length arrays are not null! ( and stream.readLine() ) | ||||
---|---|---|---|---|
| ||||
Three related things, why are zero length arrays null, why does 'null' ~ array work and why does Stream.readLine() return null on a zero length source string. I personally would like Stream.readline() to return a null ONLY at eof, if the source line is '\n' then I would prefer a zero length array returned. I tried to change the phobos src so that after the first char c = getc(); I added result = new char[0]; but still get 'null' returned I also noticed that there was default: result ~= c; but result is never assigned is this realy a safe operation, surely this should throw an exception I then tried this test prog ... import c.stdio; import stream; void printValue( char[] str ) { if ( str == null ){ printf( "array is null;\n" ); } else { printf( "array is %i chars long;\n", str.length ); } } int main( char[][] args ) { char [] ar; try { printf( "undef ... " ); printValue( ar ); printf( "new char[0] ... " ); ar = new char[0]; printValue( ar ); printf( "new char[1] ... " ); ar = new char[1]; printValue( ar ); } catch (Exception e ) { printf("Exception caught:\n"); e.print(); } return 0; } and got the output undef ... array is null; new char[0] ... array is null; new char[1] ... array is 1 chars long; to me this is very bad, new char[0] should return a zero length non null array it may be my time working with Java but having zero length non null arrays are very useful, for instance when reading from a stream a 0 length line is exactly that and a null is eof or no line. I can see that you may want to do the following char[] str = getStr(); if ( str.length > 0 ) { ... } and have 'null'.length return 0 (as it does), to save the check if ( (str!=null) && (str.length > 0) ) { ... } but still feel that `new type[0]` != null Mike. |
Copyright © 1999-2021 by the D Language Foundation