Solidity
🥻

Solidity

Variables and types

  • Local
    • Declared inside a function and are not stored on blockchain
  • State
    • Declared outside a function to maintain the state of the smart contract
    • Stored on the blockchain
  • Global
    • Provide information about the blockchain. They are injected by the Ethereum
 

Functions, Arrays, Strings, Loops and If/Else

// Define the compiler version you would be using pragma solidity ^0.8.10; // Start by creating a contract named Conditions contract Conditions { // State variable to store a number uint public num; // Array can have a compile-time fixed size or a dynamic size. string public greet = "Hello World!"; uint[] public arr; uint[] public arr2 = [1, 2, 3]; // Fixed sized array, all elements initialize to 0 uint[10] public myFixedSizeArr; // Memory variables and Storage variables can be thought of as similar to RAM vs Hard Disk. // Memory variables exist temporarily, during function execution, whereas Storage variables // are persistent across function calls for the lifetime of the contract. // Here the array is only needed for the duration while the function executes and thus is declared as a memory variable function getArr(uint[] memory _arr) public view returns (uint[] memory) { return _arr; } /* Name of the function is set. It takes in an uint and sets the state variable num. It is declared as a public function meaning it can be called from within the contract and also externally. */ function set(uint _num) public { num = _num; } /* Name of the function is get. It returns the value of num. It is declared as a view function meaning that the function doesn't change the state of any variable. view functions in solidity do not require gas. */ function get() public view returns (uint) { return num; } /* Name of the function is foo. It takes in an uint and returns an uint. It compares the value of x using if/else */ function foo(uint x) public returns (uint) { if (x < 10) { return 0; } else if (x < 20) { return 1; } else { return 2; } } /* Name of the function is loop. It runs a loop till 10 */ function loop() public { // for loop for (uint i = 0; i < 10; i++) { if (i == 3) { // Skip to next iteration with continue continue; } if (i == 5) { // Exit loop with break break; } } } }
*View
Function cant change the state of the contract
Â