Complete the code to prevent integer overflow by using a safe addition function.
function safeAdd(uint8 a, uint8 b) public pure returns (uint8) {
uint8 c = a + [1];
require(c >= a, "Overflow detected");
return c;
}The function adds two unsigned 8-bit integers. To check overflow, it adds b to a and verifies the result is not smaller than a.
Complete the code to check for underflow before subtraction.
function safeSub(uint8 a, uint8 b) public pure returns (uint8) {
require(a [1] b, "Underflow detected");
return a - b;
}Before subtracting, the code checks that a is greater than or equal to b to avoid underflow.
Fix the error in the code that causes overflow when multiplying two uint8 numbers.
function safeMul(uint8 a, uint8 b) public pure returns (uint8) {
uint8 c = a * [1];
require(b == 0 || c / b == a, "Overflow detected");
return c;
}a by itself instead of b.The multiplication must be between a and b. The check ensures no overflow happened.
Fill both blanks to create a safe division function that prevents division by zero.
function safeDiv(uint8 a, uint8 b) public pure returns (uint8) {
require(b [1] 0, "Division by zero");
return a [2] b;
}b equals zero instead of not equals.The function checks that b is not zero before dividing a by b.
Fill all three blanks to create a safe modulo function that prevents modulo by zero.
function safeMod(uint8 a, uint8 b) public pure returns (uint8) {
require(b [1] 0, "Modulo by zero");
uint8 c = a [2] b;
return c [3] b;
}The function checks that b is not zero, then calculates a % b and returns the result.