Solidity-if-else-if-statement

提供:Dev Guides
移動先:案内検索

堅牢性-if …​ else if …​ ステートメント。

*if ... else if ...* ステートメントは、 *if ... else* の高度な形式であり、Solidityがいくつかの条件から正しい決定を下せるようにします。

構文

if-else-ifステートメントの構文は次のとおりです-

if (expression 1) {
   Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
   Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
   Statement(s) to be executed if expression 3 is true
} else {
   Statement(s) to be executed if no expression is true
}

このコードについて特別なことは何もありません。 これは一連の if ステートメントであり、各 if は前のステートメントの else 句の一部です。 ステートメントは真の条件に基づいて実行され、どの条件も真でない場合、 else ブロックが実行されます。

pragma solidity ^0.5.0;

contract SolidityTest {
   uint storedData;//State variable
   constructor() public {
      storedData = 10;
   }
   function getResult() public view returns(string memory) {
      uint a = 1;
      uint b = 2;
      uint c = 3;
      uint result

      if( a > b && a > c) {  //if else statement
         result = a;
      } else if( b > a && b > c ){
         result = b;
      } else {
         result = c;
      }
      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);//access local variable
   }
}

link:/solidity/solidity_first_application [Solidity First Application]の章に記載されている手順を使用して、上記のプログラムを実行します。

出力

0: string: 3