sourcepawn
sourcepawn copied to clipboard
Expand non-constant array initialization
Currently, non-literal arrays cannot be assigned to separate arrays when the latter is declared.
public void main()
{
int Foo[3] = {1, 2, 3};
int Bar[3]; Bar = Foo; // OK
}
vs.
public void main()
{
int Foo[3] = {1, 2, 3};
int Bar[3] = Foo; // Not OK
}
Also, non-literals cannot be assigned to arrays in this way, either:
public void main()
{
float Foo = 2.0, Bar = 3.0;
float FooBar[2] = {Foo, Bar}; // Not OK
}
It would be great if the last 2 blocks were allowed in SP. Would help make some things look cleaner.
Thanks.
The limitation currently is initialization has to involve constants. So, besides the workaround in your first code block (which makes it assignment instead of initialization), you can initialize with consts:
const int a = 1;
const int b = 2;
int arr[2] = {a, b};
Understood. However using non-constants in that manner is valid C code, which made me wonder why it isn't allowed in SourcePawn.
If you're asking if the behavior can be changed, then yes, it could be. I don't have any comment about the likelihood, though I agree it'd be nice to have.
If you're asking for the technical reason, it's that when you use an array literal, the compiler actually puts the array in the data section. For your first example, somewhere inside your plugin binary, the values 1, 2, and 3 are sitting next to each other. In your other examples, since they're not constants, it won't be able to do the same thing.
The former. And I do appreciate the insight.
Yeah, certainly this is a feature we'd like to have. There's significant technical debt in the compiler to overcome this though. For every non-constant expression, we'd have to propagate that out of the initializer parser and then emit a series of evaluate and index-assignment operations. I.e.,
float x[3] = {1, 2, y};
would be generated as:
float x[3] = {1, 2, 0};
x[2] = y;
But we don't have the infrastructure to do this yet. It's a good feature request though, so let's leave it open.