i++ vs. ++i
Last Updated on 24. March 2025 by Mario Oettler
At the first glance incrementing a variable i with i++ or ++i seems to be the same. But in the background things are different.
i++ is called post-increment operator. It creates a copy of i and returns it. Then it increments i.
++i is called pre-increment operator. It increments the value immediately and returns the new value of i. The following code example shows the difference.
pragma solidity 0.8.29;
contract Incrementor{
uint256 i = 1;
uint256 j = 1;
uint256 a = 1;
function increment_01() public returns(uint256, uint256){
a = i++;
return (a, i);
}
function increment_02() public returns(uint256, uint256){
a = ++j;
return (a, j);
}
}
Function increment_01() uses the post-increment operator. It returns the following values:
a = 1,
i = 2
Function increment_02() uses the pre-increment operator. It returns the following values:
a = 2
j = 2
So, what does this have to do with gas costs? The post-increment operator (i++) makes a copy of the variable in memory. This costs gas. Hence, the pre-increment operator (++i) is cheaper as it doesn’t make a copy.
The following table shows that gas cost for a single increment.
Operator | Gas Costs |
i++ | 5585 |
++i | 5558 |