Solidity - 条件运算符


例子

尝试以下代码来了解条件运算符在 Solidity 中的工作原理。

pragma solidity ^0.5.0;

contract SolidityTest {
   uint storedData; 
   constructor() public{
      storedData = 10;   
   }
   function getResult() public view returns(string memory){
      uint a = 1; // local variable
      uint b = 2;
      uint result = (a > b? a: b);  //conditional operation
      return integerToString(result); 
   }
   function integerToString(uint _i) internal pure 
      returns (string memory) {
      if (_i == 0) {
         return "0";
      }
      uint j = _i;
      uint len;
      while (j != 0) {
         len++;
         j /= 10;
      }
      bytes memory bstr = new bytes(len);
      uint k = len - 1;
      while (_i != 0) {
         bstr[k--] = byte(uint8(48 + _i % 10));
         _i /= 10;
      }
      return string(bstr);
   }
}

使用Solidity First Application章节中提供的步骤运行上述程序。

输出

0: string: 2
solidity_operators.htm