9

I saw these code lines in cryptozombies.io:

uint id = zombies.push(Zombie(_name, _dna)) - 1;
zombieToOwner[id] = msg.sender;

I wouldn't have had a problem had there not been "- 1" after the push() function. I believe the return value of the push function has something to do with the index of the inserted object. Why is there a "-1"? Is the return value index of the next free spot available to insert the next object in the array?

14

From the Solidity documentation:

push: Dynamic storage arrays and bytes (not string) have a member function called push that can be used to append an element at the end of the array. The function returns the new length.

The function returns the new length of the array. So if there is 1 element in the array already, and I push another, that push will return the new length, which is 2. Since arrays are zero-indexed you have to subtract one from the length to get the index of the last element, which is what the code sample you posted is doing.

8

The array.push() function is only available for storage arrays that are dynamically sized. (e.g. you can't do array.push() on bytes32[10] array as that is statically sized).

In those cases the push function returns the new length of the array so the last index is always the length -1 since indexes start from 0 not 1 ;

You can check it here if you want : http://solidity.readthedocs.io/en/develop/types.html?highlight=array#members

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.