Michael Fawole
Michael Fawole

Follow

Michael Fawole

Follow
overflow and underflow in solidity

Photo by Aditya Chinchure on Unsplash

overflow and underflow in solidity

Michael Fawole's photo
Michael Fawole
·Nov 25, 2022·

2 min read

Play this article

Table of contents

  • Definition of an overflow
  • Definition of an underflow

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;
   }
}
 
Share this