unchecked en Solidity
0.8 verifica la aritmética; unchecked renuncia donde es seguro.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
// 0.8 checks arithmetic by default; unchecked opts out where
// overflow is impossible and gas is worth saving.
contract RowCounter {
uint256 public row;
uint256 public constant ROWS = 64;
function next() external returns (uint256) {
uint256 current = row;
unchecked {
row = (current + 1) % ROWS; // bounded: cannot overflow
}
return current;
}
function remaining() external view returns (uint256) {
return ROWS - row;
}
}
Cómo funciona
- Desde 0.8, el desborde revierte por defecto.
unchecked { ... }salta el chequeo donde las cotas lo permiten.- El módulo mantiene a
rowdentro de sus 64 surcos.
Palabras clave y builtins usados aquí
contractexternalfunctionpublicreturnreturnsuint256
El intento, en números
- Líneas
- 21
- Caracteres a escribir
- 484
- Tokens
- 72
- Ritmo de tres estrellas
- 60 tpm
Al ritmo de tres estrellas de 60 tokens por minuto, este intento toma unos 72 segundos.
Paso 3 de 3 en Datos y gas; paso 16 de 28 en Fundamentos del lenguaje.