I am trying to do subtraction operation using the SafeMath library. The following is my code:
pragma solidity ^0.5.1;
library SafeMath {
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
}
contract Underflow1 {
using SafeMath for uint;
uint8 num= 0;
function testf2() public returns (uint8){
//val--;
num= num.sub(1);
return num;
}
}
I am getting following error message:
browser/UF8-SM.sol:13:10: TypeError: Member "sub" not found or not
visible after argument-dependent lookup in uint8. num= num.sub(1);
^—–^
Somebody please guide me.
Zulfi.
Best Answer
The reason you are getting that error is because
num
is of typeuint8
, and thesub()
function of SafeMath is looking for typeuint256
. Additionally you declareusing SafeMath for uint;
, which confirms that it only works withuint256
(asuint
is an alias foruint256
).There are two ways to fix it:
1) Make
num
auint256
type. Your code would look as follows:2) (Not preferred) Allow SafeMath to handle type
uint8
. Your code would look as follows: