i++ vs. ++i

Published by Mario Oettler on

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.

OperatorGas Costs
i++5585
++i5558

Categories:

https://blockchain-academy.hs-mittweida.de/wp-content/uploads/2021/04/logo_bcam_rgb_gross.png

Welcome

Blockchain Academy

Continue with credential

No account yet?

Powered by Hidy

Register with Hidy


Register
Sign in

We need the following credential to register:

please select:

To create a new account, we need the following data from you:

We would appreciate the following additional information from you for the creation of your account:

Welcome

Blockchain Academy

Continue with credential

Already have an account?

Powered by Hidy

Sign in with Hidy


Register
Sign in

We need the following credential to log in:

please select:
Do you need assistance?
Click here to open chat.

Privacy Notice: This chat sends your questions to an external AI server.
How can we help you?
  • Please note: All questions, chat history, and feedback are sent to an external AI server for processing. Do not share sensitive personal information.

    All responses are generated by AI. Independently verify and fact-check all information before use.
  • No Chat History yet, start talking...