Consider the following Solidity function that modifies an array passed as memory and storage. What will be the final value of myArray after calling modifyArrays?
pragma solidity ^0.8.0; contract Test { uint[] public myArray = [1, 2, 3]; function modifyArrays(uint[] memory memArray) public { memArray[0] = 100; myArray[1] = 200; } }
Remember that memory arrays are copies and changes to them do not affect storage arrays.
The memArray is a copy of the array passed in memory. Changing memArray[0] does not affect myArray. However, myArray[1] is changed directly in storage, so it updates to 200.
What happens if you try to modify a calldata array inside a Solidity function?
pragma solidity ^0.8.0; contract Test { function modifyCalldata(uint[] calldata data) public pure { data[0] = 10; } }
Think about the mutability of calldata parameters.
calldata is read-only. Trying to assign a value to an element causes a compilation error.
calldata over memory for function parameters?Which of the following is the main advantage of using calldata instead of memory for external function parameters in Solidity?
Think about how data is passed and stored in Ethereum transactions.
calldata is a read-only area where function arguments are stored. Using it avoids copying data into memory, saving gas.
What will be the output of the following Solidity code snippet?
pragma solidity ^0.8.0; contract Test { uint[] public arr = [1, 2, 3]; function test() public returns (uint) { uint[] storage ref = arr; uint[] memory copy = arr; ref[0] = 10; copy[1] = 20; return arr[0] + arr[1]; } }
Remember that storage references affect the original array, but memory copies do not.
Changing ref[0] changes arr[0] to 10. Changing copy[1] does not affect arr. So sum is 10 + 2 = 12.
Which statement best explains how storage layout impacts gas costs in Solidity smart contracts?
Think about what happens when you change data stored on the blockchain.
Writing to storage costs more gas because it changes the blockchain state, which requires consensus and persistence.