1

Attempting to assign array parameters globally

bytes32[] params; (params[0], params[1]) = ("p1", "p2");

results in ParserError: Function, variable, struct or modifier declaration expected.

When moved into a function there is no longer a parser error; but, when the function is called the following error occurs Error: VM Exception while processing transaction: invalid opcode

Please advice.

0TTT0
  • 672
  • 2
  • 10
  • 20

1 Answers1

3

The first error is because you can't have an assignment outside of a function.

Moving it to a function is correct, but you're writing past the end of the array. params starts with a length of 0, but you're trying to write to it.

You can fix that by directly setting the length:

params.length = 2;
(params[0], params[1]) = ("p1", "p2");

I consider it more straightforward to use push:

params.push("p1");
params.push("p2");
user19510
  • 27,999
  • 2
  • 30
  • 48
  • So we cannot make an assignment to a storage array accept in a function? Can you explain why – 0TTT0 Jul 09 '18 at 20:51
  • 1
    Correct. That's how most programming languages in the C family work (C/C++/C#/Java, etc.). You can always put that sort of code in the constructor, which is the first executable code in the contract. – user19510 Jul 09 '18 at 21:11
  • From my understanding, it's incorrect to put any executable code outside of a function, not just assignments (well, in C-family languages there are some exceptions, but let's pretend they don't exist for the sake of not writing an eight-hundred-word simple question). Is that correct? –  Jul 10 '18 at 00:12
  • @NicHartley I think that might be slightly overbroad... for example address owner = msg.sender; probably counts as "executable code" but is allowed outside of a function. I think it's more accurate to say that the only things allowed at the contract level are variable declarations (including initialization) and functions. – user19510 Jul 10 '18 at 00:15
  • Yeah, variable initialization was one of the "exceptions" I was referring to. Good to know. Thanks! –  Jul 10 '18 at 00:17