mirror of
https://github.com/ethereum/solidity
synced 2023-10-03 13:03:40 +00:00
Documentation.
This commit is contained in:
@@ -246,21 +246,32 @@ Two's Complement / Underflows / Overflows
|
||||
=========================================
|
||||
|
||||
As in many programming languages, Solidity's integer types are not actually integers.
|
||||
They resemble integers when the values are small, but behave differently if the numbers are larger.
|
||||
For example, the following is true: ``uint8(255) + uint8(1) == 0``. This situation is called
|
||||
an *overflow*. It occurs when an operation is performed that requires a fixed size variable
|
||||
to store a number (or piece of data) that is outside the range of the variable's data type.
|
||||
An *underflow* is the converse situation: ``uint8(0) - uint8(1) == 255``.
|
||||
They resemble integers when the values are small, but cannot represent arbitrarily large numbers.
|
||||
|
||||
The following code causes an overflow because the result of the addition is too large
|
||||
to be stored in the type ``uint8``:
|
||||
|
||||
::
|
||||
|
||||
uint8 x = 255;
|
||||
uint8 y = 1;
|
||||
return x + y;
|
||||
|
||||
Solidity has two modes in which it deals with these overflows: Checked and Unchecked or "wrapping" mode.
|
||||
|
||||
The default checked mode will detect overflows and cause a failing assertion. You can disable this check
|
||||
using ``unchecked { ... }``, causing the overflow to be silently ignored. The above code would return
|
||||
``0`` if wrapped in ``unchecked { ... }``.
|
||||
|
||||
Even in checked mode, do not assume you are protected from overflow bugs.
|
||||
In this mode, overflows will always revert. If it is not possible to avoid the
|
||||
overflow, this can lead to a smart contract being stuck in a certain state.
|
||||
|
||||
In general, read about the limits of two's complement representation, which even has some
|
||||
more special edge cases for signed numbers.
|
||||
|
||||
Try to use ``require`` to limit the size of inputs to a reasonable range and use the
|
||||
:ref:`SMT checker<smt_checker>` to find potential overflows, or use a library like
|
||||
`SafeMath <https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol>`_
|
||||
if you want all overflows to cause a revert.
|
||||
|
||||
Code such as ``require((balanceOf[_to] + _value) >= balanceOf[_to])`` can also help you check if values are what you expect.
|
||||
:ref:`SMT checker<smt_checker>` to find potential overflows.
|
||||
|
||||
.. _clearing-mappings:
|
||||
|
||||
|
||||
Reference in New Issue
Block a user