VM错误:在将uint8添加到int字面量时恢复坚固性



我有这样的代码:

function somePureFunction() public pure returns(uint256){
uint8 temp = 255;
return 2 + temp;
}

这段代码给出了:

call to SimpleStorage.somePureFunction errored: VM error: revert.
revert
The transaction has been reverted to the initial state.
Note: The called function should be payable if you send value and the value you send should be less than your current balance.

但这是有效的:

function somePureFunction() public pure returns(uint256){
return 2 + 255;
}

特别是你的问题是关于temp的值,你给这个变量。当你声明一个数据类型为uint8的变量时,你必须在它里面放一个0 - 255(255除外)的值。要计算特定单位的范围,可以使用以下语句:

MaximumRange = 2*[numberOfBit]-1

的例子:

问题:我想知道uint32的范围是什么。

表达式= 2*32-1

Result = 0 - 4294967295

在您的特定情况下,如果更改这一行:

uint8 temp = 255;

与这个:

uint16 temp = 255;

it' s work successfully.

注意:您可以将当前数据类型temp变量更改为其他int数据类型,如:uint16, uint32, uint64等。您必须牢记单个数据类型的范围和您想要存储在变量中的值。