2. Variables, Data Types, and Functions
Solidity is similar to C++ or JavaScript, but it has key differences in handling data types and state variables due to the Ethereum environment.
2.1. Key Data Types
- uint (unsigned integer): Non-negative integers. Includes
uint8,uint256, etc., whereuintis an alias foruint256. - bool: True/false values.
- address: An Ethereum address (20 bytes). Used for sending Ether or interacting with other contracts.
2.2. State Variables vs. Local Variables
State variables are permanently stored on the blockchain (Storage), while local variables only exist during function execution (Memory/Stack).
contract DataTypes {
uint256 public balance = 100; // State Variable (Storage)
function checkBalance() public view returns (uint256) {
uint256 temporaryValue = 5; // Local Variable (Stack)
return balance + temporaryValue;
}
}
2.3. Function Visibility
Functions have four visibility keywords: external, public, internal, private.
- public: Callable by anyone (internal or external).
- private: Callable only from within the contract.
- internal: Callable from within the contract and derived contracts (inheritance).
- external: Callable only via external transactions (cannot be called internally).