- Mastering Ethereum
- Merunas Grincalaitis
- 482字
- 2021-06-24 15:01:04
Uints
Uints are unsigned integers, which means that they are numbers starting from zero that can't be negative.
You define them as follows:
uint public myNumber;
As you can see, you first define the type of the variable, then the visibility, and then the name of the variable. Remember that if you don't define the visibility of the variable, the variable will be public.
Uints can be of the following types:
- uint8
- uint16
- uint24
- uint32
- uint64
- uint128
- uint256
The number for each variable means the size of the uint. A uint8 type of variable will be able to store up to 256. So, the maximum variable of a uint8 variable is 256. If you want to store the number 255, the variable will work properly, but, if you want to store the number 256 as follows, then the variable will overflow, and it will reset to zero instead of 256, because it exceeds the capacity of that type of variable:
uint8 public myNumber = 256;
When you try to store a value 256, the variable resets because it starts at zero, so the capacity is the calculated number minus one.
What happens when you try to store another number that exceeds the capacity of the variable, such as 300? Then, the value of the variable will be 44. So, input the following:
uint8 public myNumber = 300;
It will become the following:
uint8 public myNumber = 44;
Note that you can't assign a value that is bigger than the variable's capacity, because you'll get a compilation error in some cases when trying to deploy your contract. The overflow problem can happen when you have a function that receives a uint8, but the user inputs a value bigger than 255.
This is the same thing with uint16, which has a maximum value of 65536-1. Likewise, uint24 has a maximum value of 16777216-1. The uint32 variable has a maximum value of 4294967296-1. The uint64 variable has a maximum value of 1844674407370955e19-1. The uint128 variable has a maximum value of 3402823669209385e38-1. The uint256 variable has a maximum value of 1157920892373163e77-1.
As you can see, the maximum number grows pretty quickly. This is great to avoid overflows when you are dealing with big numbers.
On the other hand, you have the problem of underflows. These happen when you try to store a negative number into a uint. For instance, try to do this:
uint8 public myNumber = -5;
You'll get the following:
uint8 public myNumber = 251;
This happens for the same reason as overflows; you are going from zero to the biggest number possible that that variable can hold.
Those problems can result in heavy vulnerabilities. That's why it's important that you check that the values that the user inputs in your functions are within the range of acceptable numbers. You'll later see how to verify inputs from functions with a global function called require().