Skip to content

Solidity Primitive Data Types

This example demonstrates the basic primitive data types available in Solidity and how to use them.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract PrimitiveDataTypes {
    // Boolean type
    bool public isActive = true;

    // Integer types
    int8 public smallNumber = -128;    // -128 to 127
    uint8 public smallUnsigned = 255;  // 0 to 255
    int public signedNumber = -1234;   // default int256
    uint public unsignedNumber = 1234; // default uint256

    // Address types
    address public contractOwner = 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4;
    address payable public payableAddress; // can receive Ether

    // Byte types
    bytes1 public singleByte = 0xFF;   // Fixed-size byte array (1 byte)
    bytes public dynamicBytes;         // Dynamic-size byte array

    // Fixed-point numbers (not fully supported yet)
    // fixed public fixedNumber;       // Fixed point number

    // Function to demonstrate type assignments
    function updateValues(
        bool _isActive,
        uint8 _small,
        address _owner,
        bytes1 _byte
    ) public {
        isActive = _isActive;
        smallUnsigned = _small;
        contractOwner = _owner;
        singleByte = _byte;
    }

    // Function to demonstrate type conversions
    function typeConversions() public pure returns (uint) {
        int16 smallInt = 250;
        uint32 mediumUint = uint32(smallInt); // explicit conversion required
        return mediumUint;
    }
}

What's happening here?

  1. Boolean (bool)

    • Can only be true or false
    • Default value is false
  2. Integers

    • int: Signed integers (positive and negative)
    • uint: Unsigned integers (only positive)
    • Size variants from 8 to 256 bits (int8, int16, ..., int256)
    • Default size is 256 bits
  3. Address

    • Holds a 20-byte Ethereum address
    • address: Cannot receive Ether
    • address payable: Can receive Ether
  4. Bytes

    • bytes1 to bytes32: Fixed-size byte arrays
    • bytes: Dynamic-size byte array
    • Used for raw byte data

Key Concepts Demonstrated

  • Variable declaration and initialization
  • Different integer sizes and their ranges
  • Type conversion between different sizes
  • Address types and their capabilities
  • Fixed vs dynamic byte arrays
  • Function parameters with different types

Best Practices

  1. Use the smallest data type that can safely hold your values
  2. Be explicit about integer sizes when precision matters
  3. Use explicit type conversion to prevent unintended behavior
  4. Consider gas costs when choosing between types
  5. Initialize variables to prevent undefined behavior