Unmatched static array size assignment

Andrej Mitrovic none at none.none
Wed Apr 13 13:56:31 PDT 2011


Code:

void main()
{
    static string[2] szFormat = ["%s, %s"];
}

This compiles, but this is buggy code. The first declaration should have been:
static string[2] szFormat = ["%s", "%s"];

I can't tell whether the first case is legit code. You might *want* to initialize all the elements with the same single initializer. But in that case, you would write:
static string[2] szFormat = "%s, ";

So, without the '[]'.

If you remove static from the declaration (it's still a static array, I know!), you'll get a nice runtime error:
object.Exception at src\rt\arraycat.d(31): lengths don't match for array copy

Actually it's not a nice error message since you can't even tell what causes the error.

So in retrospect:
// no error until a call to writefln,
// which could still potentially not fail => possible bugs
string[2] szFormat = ["%s, %s"];            

// error at runtime, the compiler could have caught this though
static string[2] szFormat2 = ["%s, %s"];



More information about the Digitalmars-d-learn mailing list