0

For example, if I have:

balances[from] -= tokens;
balances[from] = balances[from]-tokens;
balances[from] = balances[from].sub(tokens);

What is a difference and why should I use one rather than the other, and when ?

Edit: I am aware of differences in languages such as C, but I don't know about the Solidity.

3

The first two examples are using different syntax to accomplish the same task and will compile to identical bytecode. The third approach performs the calculation by using the SafeMath library.

Solidity has no built-in integer overflow protection. In the first two examples, if the value of tokens exceeds that of balance[from], the subtraction would cause balance[from] to underflow. SafeMath adds a require (balance[from] >= tokens) check before performing the subtraction, which reverts the transaction when an underflow would occur.

To learn more about how SafeMath works and how to implement it in your contracts, I suggest reading SafeMath to Protect from Overflows.

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.