ReasonJun

Solidity : constant 본문

Blockchain/Solidity

Solidity : constant

ReasonJun 2023. 10. 15. 21:53
728x90

A constant in Solidity is a variable whose value cannot be changed once it has been initialized. Constants are defined using the constant keyword.

 

Constants can be used to represent values that should not change, such as the maximum supply of a token or the address of a trusted contract. They can also be used to improve the readability and maintainability of your code.

 

Here is an example of how to define a constant in Solidity:

contract MyContract {
    // Constant variables are defined using the `constant` keyword.
    constant uint256 MAX_SUPPLY = 10000;

    function doSomething() public {
        // We can use the constant `MAX_SUPPLY` in our function.
        // ...
    }
}

Once the constant MAX_SUPPLY has been initialized, it cannot be changed. Attempting to change the value of a constant will result in a compiler error.

 

Constants can be used in any part of a Solidity contract, including state variables, function parameters, and local variables. They can also be used in expressions and as arguments to functions.

 

Constants can be of any type, including primitive types, arrays, mappings, and structs.

 

Here are some of the benefits of using constants in Solidity:

  • Improved readability and maintainability: Constants can make your code more readable and maintainable by making it clear which values are intended to be unchanged.
  • Reduced risk of errors: Constants can help to reduce the risk of errors by preventing accidental changes to important values.
  • Gas optimization: In some cases, using constants can lead to gas optimization. For example, if a constant is used in a function parameter, the compiler can optimize the code to avoid storing the parameter in memory. 

example : 

// SPDX-License-Identifier: MIT
pragma solidity >= 0.7.0 < 0.9.0;

contract Constants {
    // coding convension to uppercase constant variables
    address public constant MY_ADDRESS = 0x0000000000000000000000000000000000000000;
    uint public constant MY_UINT = 123;
    string public constant name = "TEST token";
    uint public constant decimals = 18;
    uint public constant INITIAL_SUPPLY = 1000 * 10 ** decimals;
    // INITIAL_SUPPLY = 1000.000000000000000000 (Use up to 18 decimal places)

    string constant test = "You can not see this";
    // If there is no 'public' mark, you cannot see the text.
}

 

Overall, using constants in Solidity is a good practice that can lead to more secure, reliable, and efficient code.

728x90

'Blockchain > Solidity' 카테고리의 다른 글

Solidity : Visibility  (0) 2023.10.15
Solidity : Operator / Shift operator  (1) 2023.10.15
Solidity : Data Type (1)  (0) 2023.10.15
Solidity : storage, memory, calldata, stack  (0) 2023.10.15
Solidity : Variable  (0) 2023.10.15
Comments