SolidityIn

Arrays and loops

Lesson 3 of 40 · Basics

Arrays hold lists of values. A fixed-size array such as uint256[3] has a set length, while a dynamic array such as address[] can grow with push and shrink with pop. You read an item with an index, and the first item is at index 0.

Reading an index that does not exist reverts the transaction. That is a safety feature: Solidity checks array bounds for you, so you cannot read outside the array.

Loops let you process every item, but they cost gas on every iteration. A loop over a list that users can keep adding to is dangerous, because it can grow until the function costs more gas than a block allows, and then nobody can call it.

Solidity has no cheap way to remove an item from the middle of an array. A common pattern is to copy the last item into the gap and call pop. This keeps the cost constant, but it changes the order of the items.

Arrays in memory have a fixed size set when you create them with new. Use them for temporary results inside a function, and use storage arrays only for data that must last.

contract Team {
    address[] public members;

    function add(address m) external {
        members.push(m);
    }
    function remove(uint256 i) external {
        require(i < members.length, "Out of range");
        members[i] = members[members.length - 1];
        members.pop();
    }
    function count() external view returns (uint256) {
        return members.length;
    }
    function firstN(uint256 n) external view returns (address[] memory out) {
        out = new address[](n);
        for (uint256 i = 0; i < n; i++) {
            out[i] = members[i];
        }
    }
}

Try it yourself

Add a function contains(address who) that loops through members and returns true if it finds who. Think about why this would be risky for a very large list.

Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.

Quick check: Why should loops over unbounded arrays be avoided?