▫️Lesson 2.2: Solidity Variables, Types, and Expressions
Module 2: Developing Smart Contracts with Solidity
Objective
To deepen your understanding of Solidity by exploring its variables, data types, and expressions. This lesson will cover how to declare variables, the types of variables available in Solidity, and how to use expressions to manipulate data within smart contracts.
Variables in Solidity
Variables in Solidity are declared as either state variables, local variables, or global variables.
State Variables: Stored on the blockchain, persist across function calls and transactions.
Local Variables: Exist only within the function context and not stored on the blockchain.
Global Variables: Provide information about the blockchain and are available to all smart contracts.
Example:
Data Types in Solidity
Solidity supports various data types, including:
Value Types: Include boolean, integer, address, and fixed-point numbers. These are always passed by value.
Reference Types: Include arrays, structs, and mappings. These can be stored in storage or memory and are passed by reference.
Special Types: Such as
bytes
,enum
, and contract types.
Example:
Expressions and Control Structures
Solidity supports control structures similar to those in JavaScript, including if-else statements, for loops, while loops, and do-while loops. Expressions in Solidity allow for the manipulation of data through operations such as addition, subtraction, multiplication, and division.
Example:
Activity: Experimenting with Data Types and Control Structures
Create a new contract: Use Remix IDE to create a contract that demonstrates the use of different data types and control structures.
Implement a function: Write a function that uses if-else statements to perform different arithmetic operations based on input parameters.
Test your contract: Deploy your contract in Remix and test the function with various inputs to observe the outcomes.
Exercise
Practical Exercise:
Extend the
ControlStructuresExample
contract by adding a function that decrements thecount
variable by a specified value, but never lets it go below 0. Use control structures to ensurecount
cannot become negative.
This lesson has expanded your knowledge of Solidity by introducing variables, data types, and control structures. Understanding these concepts is crucial for writing efficient and effective smart contracts.
Last updated