array setting : Whats going in here?

H. S. Teoh hsteoh at qfbox.info
Sat Oct 7 00:49:39 UTC 2023


On Sat, Oct 07, 2023 at 12:00:48AM +0000, claptrap via Digitalmars-d-learn wrote:
> 
> char[] foo;
> foo.length = 4;
> foo[] = 'a'; // ok sets all elements
> foo[] = "a"; // range error at runtime?
> foo[] = "ab"; // range error at runtime?
> 
> So I meant to init with a char literal but accidently used double
> quotes.  Should that even compile? Shouldn't the compiler at least
> complain when trying to init with "ab"?

If you want initialization, don't slice the target array. For example:

	char[] foo = "a";

Or:

	char[] foo;
	...
	foo = "a";

When you write `foo[]` you're taking a slice of the array, and in that
case if the lengths of both sides of the assignment don't match, you'll
get a runtime error.


T

-- 
Always remember that you are unique. Just like everybody else. -- despair.com


More information about the Digitalmars-d-learn mailing list