# When a Solidity storage reference changes contract state

Both functions below assign 27 to a field called `score`. Call `changeStorage(27)` and the contract stores 27. Call `changeCopy(27)` on a fresh contract and the function returns 27 while the stored score stays at 10.

The difference is on the assignment line. A local `storage` variable refers to the existing record. A `memory` variable initialized from storage gets a copy. You can check both outcomes in the same Foundry test file.

Save this as `test/DataLocations.t.sol` in a Foundry project. The file uses Solidity 0.8.30 and does not need a test library.

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract Scoreboard {
    struct Record {
        uint256 score;
    }

    Record private current = Record(10);

    function score() external view returns (uint256) {
        return current.score;
    }

    function changeStorage(uint256 value) external {
        Record storage entry = current;
        entry.score = value;
    }

    function changeCopy(uint256 value) external view returns (uint256) {
        Record memory entry = current;
        entry.score = value;
        return entry.score;
    }
}

contract DataLocationsTest {
    function testStorageReferenceChangesState() public {
        Scoreboard board = new Scoreboard();

        board.changeStorage(27);

        require(board.score() == 27, "expected a state change");
    }

    function testMemoryCopyLeavesStateAlone() public {
        Scoreboard board = new Scoreboard();

        require(board.changeCopy(27) == 27, "expected the changed copy");
        require(board.score() == 10, "expected the original state");
    }
}
```

Run just these two tests.

```sh
forge test --match-contract DataLocationsTest --use 0.8.30
```

Each test deploys a fresh contract. The storage test reads state after changing the reference. The memory test checks the returned copy and then reads the stored score separately. Both passed with Forge 1.7.1 and Solidity 0.8.30.

If a function is only meant to preview a change, test the stored value as well as the return value. The return value alone looks the same in both cases.

[Read the broader guide to storage, memory and calldata](https://fone.cc/insights/evm-data-locations-storage-memory-calldata-mappings/?utm_source=hashnode&utm_medium=referral&utm_campaign=hashnode_data_locations_20261123)

[Solidity reference types and assignment rules](https://docs.soliditylang.org/en/latest/types.html#data-location-and-assignment-behavior)

