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.

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");
  • So we cannot make an assignment to a storage array accept in a function? Can you explain why – 0TTT0 Jul 9 '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 9 '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? – Nic Hartley Jul 10 '18 at 0: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 0:15
  • Yeah, variable initialization was one of the "exceptions" I was referring to. Good to know. Thanks! – Nic Hartley Jul 10 '18 at 0:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.