[Solidity] How to write constant?

This section explains how to write constant in Solidity.

Syntax

To write constant in Solidity, use the constant modifier.

data type constant variable name = value;

Sample Code

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

contract Test {
    // constant
    uint constant gToKg = 1000;

    function getGram(uint kg) public pure returns(uint) {
        return kg * gToKg;
    }

}

As for constant, they are almost the same as in other programming languages.

タイトルとURLをコピーしました