Understanding uint Overflows and Underflows — Solidity (Ethereum)

Alber Erre
⏱️ 3 min Blockchain
2 min readApr 19, 2018

--

If you use Python or JavaScript as regular basis, you may not be aware of Overflows and Underflows. Although, if you have played around with C++ or C#, you maybe know what I am talking about.

In computing, the compiler needs to understand what input types your code is providing. This is not a big deal while using high-level languages, like Python, but becomes more important as you develop towards low-level layers.

Therefore, could Solidity be considered as a Low-level language? — nope.

However, it has Low-level type control with uint variables, as the blockchain needs to save as much gas as possible during transactions. Thus, certainly could be considered as a kinda-low-level language regarding variable types.

What Overflows and Underflows mean?

Short answer

Once an uint (unsigned integer) reaches its byte size, the next element added will return the first variable element — This is more clear using an example.

Example answer

Let’s say we have a uint8, which can only have 8 bits. That means the largest number we can store is binary 11111111 (or in decimal, 2^8 - 1 = 255).

Take a look at the following code. What is number equal to at the end?

uint8 number = 255;
number++;

Under this example, we just caused an Overflow — so number is now equal to 0, even though we increased it. (If you add 1 to binary 11111111, it resets back to 00000000, like a clock going from 23:59 to 00:00).

An Underflow is similar, where if you subtract 1 from a uint8 that equals 0, it will show 255 (because uints are unsigned in solidity, and therefore cannot be negative). Info source: Loom Network

Conclusions

As a good practice, it seems unlikely that a uint256 will neither Overflow nor Underflow while updating values as 2^256 is a really a huge number. Thus, we should use this variable type to make secure things.

Although, in case your application really needs to optimize resources, you should go ahead with lower types (uint32, uint16, unit8). Just remember, take these concepts into account to avoid security breaches and hacks.

I hope this have helped to clarify Overflows and Underflows in Solidity!

Cheers, Alber Erre.

--

--

Alber Erre
⏱️ 3 min Blockchain

Messy Blockchain Adventures 🚀 & Front End Development