How to handle floating-point numbers in Ethereum smart contracts?

Viewed 97

recently, I’ve been learning about the development of Ethereum smart contracts. I have a question about the following code; the result obtained by the “a” method is 4. This result is the same as my common sense understanding because, in the floating-point processing, the corresponding floating-point number will be intercepted when running. However, when I call the method “b”, the result is 5. I don't understand this result very well. Is it because the compiler has optimised during the compilation process to calculate the outcome directly and store it? Thanks a lot, guys.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
 
contract Test {
    uint constant c = 5;
    
    function a() public pure returns(uint){
        return c/2 + c/2;
    }   
    
    function b() public pure returns(uint){
        return 5/2 + 5/2;
    }
}
1 Answers

It seems that compiler optimize the return 5/2 + 5/2; line. In assembly output, after compiling with solc-v0.8.13 --asm --optimize-run=100000, there are following lines:

        /* "Test.sol":215:224  5/2 + 5/2 */
      0x05
        /* "Test.sol":208:224  return 5/2 + 5/2 */
      swap1
      pop

What indicates that 0x05 value is directly returned from function call.

In function a the integer division is rounded down, so returned value is 0x04. Compiler doesn't optimize this line, even though it operates on constant and literals, and allows to run integer division on EVM.

Worth mentioning is fact, that solidity is a language under continous development. So it's possible, that future compiler version will optimize code in such a way that functions in this example will give both the same results.

Related