Nuel geek

Posted on

# Overflow and Underflow in Solidity

It is important to be grounded in the basics of any technology you decide to play for the long term. In this article, we will be looking into Underflow and Overflow in solidity.

# Overflow

Overflow is a state a uint (unsigned integer) reaches its byte size, the next element added will return the first variable element (default variable value). The byte size of uint Is 255 which means once it gets to the max it resets to 0.

Illustrated Below:

``````uint16 number = 65535;
return number++;
// this returns 0 because it has gotten to the max
``````

# Underflow

Similar to overflow, underflow is a state where an uint16 if subtracted by 1 equals 0, it will show 65535 (because uints are unsigned in solidity, and therefore cannot be negative)

Illustrated Below:

``````uint16 number ; // number here is equal to 0
return number--;
// this returns 65535 because it has gotten to the Minimum
``````

Overflows are very common in solidity and must be checked for with control statements such as:

``````if(a + c > a) {
a = a + c;
}
``````

Now you understand the Overflow and Underflow concepts, you need to pay attention while writing your codes, and also keep in view what values the variable will hold because once a smart contract is deployed, it is immutable.

An easier alternative is to use OpenZeppelin's SafeMath library (Docs & Github) which automatically checks for overflows in all the mathematical operators. The resulting code looks like this:

``````a = a.add(c);
``````

If there is an overflow, the code will revert.

I hope this has helped you to gain an overview of Overflows and Underflow in Solidity and navigate better in these scenarios!

## Want to rep DEV and be comfy at the same time?

Check out our classic DEV shirt — available in multiple colors.