0

I am using a simple solidity code:

pragma solidity ^0.6.0;


contract Counter {
uint public count = 1;

function incrementCount() public {
    ++count; // one way to do this
    count++; //another way to do this
}

}

since solidity is inspired by C, I am wondering if there is any difference between prefix and postfix increment.

1

Like in other programming languages, in Solidity the prefix/postfix operator means that the place of the ++ or -- determines what will happen next.

From the docs:

a++ and a-- are equivalent to a += 1 / a -= 1 but the expression itself still has the previous value of a. In contrast, --a and ++a have the same effect on a but return the value after the change.

Example:

pragma solidity ^0.8.4;

contract Counter {
 
    uint public count = 1;

    function incrementPrefixCount() public returns (uint) {
        return (++count); // returns 2
    }
    
    function incrementPostfixCount() public returns (uint) {
        return (count++); // returns 1
    }
}

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.