contract SomeCon {
    using SomeLib for uint256;

    uint256 a = 2;
    uint256 b = 3;

    function addNum() public view returns (uint256) {
        return a.add(b); //add() is a function in SomeLib

Greeting everyone, now my confusion is in the above code, why are we adding functions to data types ? For instance a.add(b), I mean data types are for storing data, what benefit (and how) it really brings in terms of Gas Efficiency if data types are used in this way (that is alongside storing data, functions are also being attached to it) ..?

Thank You

1 Answer 1


The library that is used here is the SafeMath (https://docs.openzeppelin.com/contracts/2.x/api/math) library that was initially invented to solve the integer overflow/underflow problem, and is helpful in Solidity versions < 0.8.0, when the underflow/overflow was possible.

It's a checked math library.

In your example, a.add(b) means that all you are doing here is adding b to a (b + a), but also checking that the result doesn't overflow the 256-bit integer slot. That kind of overflow could happen if b = type(uint256).max and a >= 1 here.

In Solidity >= 0.8.0, the underflow/overflow problem doesn't exist anymore, so you can generally use normal Solidity built-in math operands if your code is written for Solidity ^=0.8.0.


  • 1
    Thanks Mila,. basically I understand that or the SafeMath Library. Basically I'm asking even for other general libraries, what really is the benefit (and how) in terms of Gas Efficiency if data types are used in this way (attaching functions to it) ..? thanks.
    – Asif5566
    Feb 9 at 0:43
  • I doubt it helps efficiency, probably doesn't really affect that at all, in most cases the idea of using libraries for a particular data type is to have additional functionality, and a more controlled behavior. So just adding some features on top of Solidity.
    – Mila A
    Feb 9 at 15:18

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.