Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow unchecked increments of for loops indexes #11721

Closed
The-3D opened this issue Jul 30, 2021 · 2 comments
Closed

Allow unchecked increments of for loops indexes #11721

The-3D opened this issue Jul 30, 2021 · 2 comments

Comments

@The-3D
Copy link

The-3D commented Jul 30, 2021

Abstract

After the (welcomed) introduction of the checked math operators in solidity 0.8.x, developers can allow safe unchecked operations by wrapping them in a unchecked {} block. Safety checks of course apply to pre and post increment/decrement operators (++/--) which are commonly used to increase indexes in for loops; unfortunately the safety checks in this case are enabled by default, and there is no way of disabling it in a developer friendly way. This may force to refactor the for loop in a while, or change the for increment in an unnatural way. Not doing it can get (very) expensive.

Motivation

Loops are in most cases bounded by definition (the bounding is represented by the exit condition). Therefore in the vast majority of cases, checking for overflows is really not needed, and can get very gas expensive. Consider the following examples:

pragma solidity ^0.8.0;

contract Test1 {
    
    
    function loop() public pure {
        
        for(uint256 i = 0; i < 100; i++) {
        }
        
    }
}
pragma solidity ^0.8.0;

contract Test {
    
    
    function loop() public pure {
        
        for(uint256 i = 0; i < 100;) {
            
            unchecked {
                i++;
            }
        }
        
    }
}

loop() in Test1 costs more than 31K gas, vs 25.5K gas for loop() in Test2

Specification

allow to specify unchecked increments in for loops as follows

for(uint256 i = 0; i < 100; unchecked i++)

@hrkrshnn
Copy link
Member

hrkrshnn commented Aug 2, 2021

This has been proposed and discussed in #10698 and #10695

@chriseth
Copy link
Contributor

chriseth commented Aug 2, 2021

The solution for now is to define a function function uncheckedInc(uint x) pure returns (uint) { unchecked { return x + 1; } } and use it as

 for(uint256 i = 0; i < 100; i = uncheckedInc(i) {
    ...
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants