28

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?

Kuelf Deez
  • 576
  • 2
  • 7
  • 15

4 Answers4

29

From the Solidity documentation:

push: Dynamic storage arrays and bytes (not string) have a member function called push() that you can use to append a zero-initialised element at the end of the array. It returns a reference to the element, so that it can be used like x.push().t = 2 or x.push() = b.

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.

Edit: As pointed out by @user8555937, this is no longer true as of Solidity 0.6.0. The push function no longer has a return value

alper
  • 8,395
  • 11
  • 63
  • 152
natewelch_
  • 12,021
  • 1
  • 29
  • 43
12

Solidity 0.6.0 has included some breaking changes :

The function push(value) for dynamic storage arrays does not return the new length anymore (it returns nothing).

The documentation now reads as is :

push(x): Dynamic storage arrays and bytes (not string) have a member function called push(x) that you can use to append a given element at the end of the array. The function returns nothing.

You must now use the .length attributes. In your case :

zombies.push(Zombie(_name, _dna));
uint id = zombies.length - 1;
Xavier59
  • 532
  • 3
  • 9
11

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

Kaki Master Of Time
  • 3,060
  • 4
  • 19
  • 44
0

I think .push() really means append a new element in array in most other languages.

In order to return the length of the array, it really makes more sense to have .length.

Shane Fontaine
  • 18,036
  • 20
  • 54
  • 82