Solidity-021 StorageTomemoryValueTypeAssignment

发布时间:2024年01月22日

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.9;

// Define a contract named StorageTomemoryValueTypeAssignment

contract StorageTomemoryValueTypeAssignment {

? ? // Declare a state variable 'stateVar' of type uint (unsigned integer)

? ? // and initialize it with the value 20.

? ? // This variable is stored on the blockchain and its state persists

? ? // across function calls.

? ? uint stateVar = 20;

? ? // Define a function 'getUInt' that is public and returns an unsigned integer.

? ? // This function demonstrates how assignment works between storage and memory variables.

? ? function getUInt() public returns (uint) {

? ? ? ? // Declare a local variable 'localVar' of type uint and initialize it with 40.

? ? ? ? // This variable is stored in memory, meaning its value is only temporary and

? ? ? ? // will be lost once the function execution completes.

? ? ? ? uint localVar = 40;

? ? ? ? // Assign the value of 'stateVar' (which is 20) to 'localVar'.

? ? ? ? // After this line, 'localVar' will hold the value 20.

? ? ? ? localVar = stateVar;

? ? ? ? // Update the state variable 'stateVar' to a new value, 50.

? ? ? ? // This change is written to the blockchain and persists beyond this function call.

? ? ? ? stateVar = 50;

? ? ? ? // Return the value of 'localVar'.

? ? ? ? // Despite the change in 'stateVar' above, 'localVar' retains its value of 20,

? ? ? ? // demonstrating that value types are copied when assigned from storage to memory.

? ? ? ? return localVar; // returns 20

? ? }

}

//Deploy screenshot:

文章来源:https://blog.csdn.net/m0_61408373/article/details/135756193
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。