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;

}

Rishi Jain
  • 43
  • 4

1 Answers1

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

Foxxxey
  • 4,307
  • 1
  • 6
  • 22