Empty VS null array?

anonymous anonymous at example.com
Thu Oct 17 16:14:50 PDT 2013


On Thursday, 17 October 2013 at 22:50:22 UTC, ProgrammingGhost 
wrote:
> How do I find out if null was passed in? As you can guess I 
> wasn't happy with the current behavior.
>
> Code:
>
> 	import std.stdio;
>
> 	void main() {
>
> 		fn([1,2]);
> 		fn(null);
> 		fn([]);
> 	}
> 	void fn(int[] v) {
> 		writeln("-");
> 		if(v==null)
> 			writeln("Use default");
> 		foreach(e; v)
> 			writeln(e);
> 	}
>
> Output
>
> 	-
> 	1
> 	2
> 	-
> 	Use default
> 	-
> 	Use default

On Thursday, 17 October 2013 at 22:51:24 UTC, ProgrammingGhost 
wrote:
> Sorry I misspoke. I meant to say empty array or not null passed 
> in. The 3rd call to fn is what I didn't like.

null implicitly converts to []. You can't distinguish them in fn.

You could add an overload for typeof(null), but that only catches 
the literal null, probably not what you'd expect:

import std.stdio;
void fn(typeof(null) v) {
	writeln("-");
	writeln("Use default");
}
void fn(int[] v) {
	writeln("-");
	foreach(e; v)
		writeln(e);
}
void main() {
	fn([1,2]);
	fn(null);
	fn([]);
	int[] x = null;
	fn(x);
}
----
-
1
2
-
Use default
-
-


More information about the Digitalmars-d mailing list