2

Why does it give a different answer for variable d

pragma solidity >=0.8.0 < 0.9.0;

contract Exercise{
    uint256 a = 2;
    
    uint256 public c = a + a++; 
    uint256 public d = a + a++; // here why does a + (a++) give 7 but (a++) + a give 6 
    uint public e = a;
}

1 Answer 1

5

Because of how a++ works. It returns a, then increments it. a + (a++); equals a + a, and the next time a is going to be accessed, its value will have been incremented, and (a++) + a is a + a, but a has been incremented before its value is read the second time. Heres another question about the ++ operator

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.