I have this contract where I use inline assembly to add two numbers.
pragma solidity ^0.8.0;
contract Test {
function add(uint a, uint b) external {
assembly {
let sum := add(a,b)
mstore(mload(0x40), sum)
}
}
}
Now the question is, how to write variable sum
to storage? In other words, how to make this sum
persistent?
Best Answer
Add the following line at the end of your assembly -
That will store
sum
value into the slot of contract variablevalue
.You can also remove the
mstore
and local varsum
and write directly to the variable -Take into consideration this doesn't handle arithmetic overflow, this is not safe to use if input number
a + b
is larger thanuint256
.