overflow and underflow in solidity
Table of contents
Hello readers, in this article I will be explaining explicitly overflow and underflow in solidity. Before I define what overflow and underflow are, you need to know about unsigned integer(uint). Overflow and underflow happens because of uint and reason being that uint in solidity has a maximum and minimum value which are 0 ≤ x ≤ 2**256 -1.
0 ≤ x ≤ 2**256 -1
The above means the range of uint is between zero and 2 raise to power of 256 -1. Now let me define what an overflow is.
Definition of an overflow
An overflow will happen in solidity if the maximum value of uint is exceeded for example if just 1 is added to 2**256 -1, it will cause an overflow.
Definition of an underflow
An underflow happens in solidity if the minimum value of uint is exceeded for example the minimum value is zero, if just 1 is removed from zero, it will lead to an underflow.
Let write a code to practicalize this.
pragma solidity ^0.8.0;
contract Adisotech{
uint public zero =0;
uint public max = 2**256 -1;
}
Declare two state variables, named zero and max respectively. Their data-type is uint and they are set to public. Equate zero to 0 and max to the maximum number.
Next is to create a function named increasemaxby1 which will add one to the max in order to cause an overflow.
function increasemaxby1() public {
max = max +1;
}
Brilliant, the next step is to crease function decreasezeroby1 which will remove 1 from zero in order to cause an underflow.
function decreasezeroby1() public {
zero = zero - 1;
}
Congratulations, you have completed the code for overflow and underflow in solidity. Here is the full code.
pragma solidity ^0.8.0;
contract Adisotech{
uint public zero =0;
uint public max = 2**256 -1;
function increasemaxby1() public {
max = max +1;
}
function decreasezeroby1() public {
zero = zero - 1;
}
}
Subscribe to my newsletter
Read articles from Michael Fawole directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Michael Fawole
Michael Fawole
Michael Fawole is a Blockchain and web application developer with 7+ years of experience and 3+ years plus of experience in blockchain dapp development. He is also delivering training on blockchain ( Solidity, web3 and react js ) and php language. He also helps start-ups and companies to setup blockchain practice and incorporating blockchain into existing project. Techstack (Blockchain): Solidity, web3 js and react js. Techstack (Webapp): Php and Mysql.