0

I got the code

pragma solidity 0.8.4;

contract AddOverflow {

    uint256 public  a = 1;     
    uint256 public  b = 2;     
    uint256 public  c; 
   
    function add() public returns (uint256) {
        c = unchecked {a + b};
        return c;
    }
  
}

when I compile it using Remix it gives the error:

Parser error: expected primary expression.

The problem is with the use of unchecked.

Can anyone help please?

1

Using the Solidity docs for guidance, it looks like you won't be able to do variable assignment inside the unchecked block. You could do something like this:

function subUnchecked(uint256 a, uint b) view public returns(uint256) {
    unchecked { return a - b ;}
}

While this doesn't save the result in a variable, you could save the result of the function call in a variable:

function callUnchecked(uint256 a, uint256 b) public {
    c = subUnchecked(a, b);
}

Which will set c to the max value of uint256.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.