Incrementing numbers in Solidity is straightforward:
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.17;
contract Counter {
uint public count = 1;
function incrementCount() public returns (uint) {
count++; // or count += 1
return count;
}
function decrementCount() public returns (uint) {
count--; // or count -= 1
return count;
}
function incrementCountByX(uint x) public returns (uint) {
return count += x;
}
function decrementCountByX(uint x) public returns (uint) {
return count -= x;
}
}
However, developers should consider the effect prefix (++i/--i) and postfix (i++/i--) operators have on return values in advanced use cases. From the docs:
a += eis equivalent toa = a + e.a++anda--are equivalent toa += 1/a -= 1but the expression itself still has the previous value ofa. In contrast,--aand++ahave the same effect onabut return the value after the change.
For example:
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.17;
contract Counter {
uint public count = 1;
function incrementCountPrefix() public returns (uint) {
// the count variable is incremented and the function
// will return 2 (or the value after the operation)
return (++count);
}
function incrementCountPostfix() public returns (uint) {
// the count variable is incremented but the function
// will return 1 (or the value prior to the operation)
return (count++);
}
}