Solidity Constants

whiteboard crypto logo
Published by:
Whiteboard Crypto
on

Constants in Solidity are variables that cannot be modifier once they are deployed. The purpose of this is to prevent vulnerabilities from changing important variables that shouldn’t ever change in the contract’s life.

Using constants also saves on the gas costs associated with deploying and using a contract.

// SPDX-License-Identifier: MIT
pragma solidity 0.8.13;

contract exampleOfConstants{
    //usually constant variables are capitalized
    address public constant MY_ADDRESS = 0x0000000000000000000000000000000000000001;
    int public constant MY_UINT = 123456789;
    string public constant domain = "whiteboardcrypto.com";

}

Please note that Solidity will not let you global variables such as block.timestamp or msg.sender to declare and initialize constant variables. You can use the keccak256 function, though.

If you try to change a constant in a future line of code, you’ll receive an error.

whiteboard crypto logo

WhiteboardCrypto is the #1 online resource for crypto education that explains topics of the cryptocurrency world using analogies, stories, and examples so that anyone can easily understand them. Growing to over 870,000 Youtube subscribers, the content has been shared around the world, played in public conferences and universities, and even in Congress.