1

I'm trying to insert an address into an address type dynamic array. It works well when I do the operation inside a function. There are no errors and the elements are properly pushed into the array.

pragma solidity ^0.5.2;

contract Random {
    address[] public participants;

    function addParticipant() public {
        participants.push(0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c);
        participants.push(0x583031D1113aD414F02576BD6afaBfb302140225);
        participants.push(0xdD870fA1b7C4700F2BD7f44238821C26f7392148);
    }
}

But when I try to do it without a function it shows an error.

Error: Expected identifier but got '('

pragma solidity ^0.5.2;

contract Random {
    address[] public participants;

    // function addParticipant() public {
        participants.push(0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c);
        participants.push(0x583031D1113aD414F02576BD6afaBfb302140225);
        participants.push(0xdD870fA1b7C4700F2BD7f44238821C26f7392148);
    // }    
}

Please advise.

1
  • What are you trying to accomplish by doing it outside of a function, or how do you expect it to work ?
    – sp4c3
    Jan 30, 2019 at 17:42

1 Answer 1

2

You can only declare state variables and set initial values outside of functions. No processing. This is mapping out how storage slots will be assigned and possibly setting value, but no more.

However, you can define a constructor to run once when the contract is deployed. This is the appropriate place for an initialization process.

address[] public array;

constructor() public {
  array.push( ...
}

Hope it helps.

2
  • Thank you for your reply. If processing can be done only inside the function, how can I use the processed result for another operation without explicitly calling the function? Can it be done in the dapp frontend?
    – shscs911
    Jan 31, 2019 at 3:48
  • Functions can be called by software clients, other functions or functions in other contracts. They can return data. They can access state data. Dapps can inspect contract functions or send transactions to functions. You could do worse than limiting the contract to safeguarding the essential truths and relying on smart clients to attend to everything that doesn't require network consensus, e.g. interpretation. Jan 31, 2019 at 4:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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