Consider the following Solidity function that uses uint8 type. What will be the value of result after calling testUnderflow()?
pragma solidity ^0.8.0; contract Test { uint8 public result; function testUnderflow() public { uint8 x = 0; unchecked { x = x - 1; } result = x; } }
Think about how unchecked blocks affect arithmetic in Solidity.
In Solidity 0.8.0 and above, arithmetic operations revert on overflow/underflow by default. However, inside an unchecked block, these checks are disabled. Since uint8 is an 8-bit unsigned integer, subtracting 1 from 0 wraps around to 255.
Choose the most accurate description of integer overflow in the context of blockchain smart contracts.
Think about what happens when a number is too big for its type.
Integer overflow happens when a value goes beyond the maximum limit of its data type, causing it to wrap around to a low value, often zero or near zero, which can cause unexpected behavior in smart contracts.
The following Solidity function is intended to add two uint8 numbers safely. However, it sometimes returns incorrect results without errors. What is the cause?
pragma solidity ^0.8.0; contract SafeAdd { function add(uint8 a, uint8 b) public pure returns (uint8) { unchecked { return a + b; } } }
Consider what unchecked does to arithmetic operations.
The unchecked block disables Solidity's default overflow checks introduced in 0.8.0. This means if a + b exceeds 255 for uint8, it wraps around silently, causing incorrect results without errors.
Given Solidity 0.8.0 or newer, which code snippet will cause a compile-time or runtime error due to integer overflow?
Remember how Solidity 0.8+ handles overflow by default.
In Solidity 0.8+, arithmetic overflow causes a runtime error unless inside an unchecked block. Option D adds 1 to 255 without unchecked, causing a runtime revert. Options B and D use unchecked so no error occurs. Option D subtracts 1 from 0 without unchecked, also causing a runtime error, but the question asks for overflow, not underflow.
Consider the following Solidity contract snippet. After calling populate(), how many keys will the balances mapping contain?
pragma solidity ^0.8.0; contract MappingTest { mapping(uint256 => uint256) public balances; function populate() public { for (uint8 i = 0; i <= 255; i++) { unchecked { balances[i] = i + 1; } } } }
Consider the effect of uint8 overflow during the for loop increment.
Although the loop condition suggests it runs 256 times (i from 0 to 255 inclusive), after executing the body for i=255, the increment 'i++' performs 'i = i + 1' on uint8 (255 + 1 = 256), which overflows. Since this operation is outside the unchecked block, Solidity 0.8+ reverts the transaction. The revert rolls back all storage changes, leaving the balances mapping with 0 keys.