Solidity – break与continue

  • continue – 跳出本次循环,继续执行接下来的循环
  • break – 跳出循环(或跳出代码块)

break 示例

pragma solidity ^0.5.0;

contract SolidityTest {
   uint storedData; 
   constructor() public{
      storedData = 10;   
   }
   function getResult() public view returns(string memory){
      uint a = 1; 
      uint b = 2;
      uint result = a + b;
      return integerToString(result); 
   }
   function integerToString(uint _i) internal pure 
      returns (string memory) {

      if (_i == 0) {
         return "0";
      }
      uint j = _i;
      uint len;

      while (true) {
         len++;
         j /= 10;
         if(j==0){
            break;   // break 语句跳出循环
         }
      }
      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 – 第一个程序中的步骤,运行上述程序。

输出

0: string: 3

continue 示例

pragma solidity ^0.5.0;

contract SolidityTest {
   uint storedData; 
   constructor() public{
      storedData = 10;   
   }
   function getResult() public view returns(string memory){
      uint n = 1;
      uint sum = 0;

      while( n < 10){
         n++;
         if(n == 5){
            continue; // 当n的和是5时,跳过n。
         }
         sum = sum + n;
      }
      return integerToString(sum); 
   }
   function integerToString(uint _i) internal pure 
      returns (string memory) {

      if (_i == 0) {
         return "0";
      }
      uint j = _i;
      uint len;

      while (true) {
         len++;
         j /= 10;
         if(j==0){
            break;   // break跳出循环
         }
      }
      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 – 第一个程序中的步骤,运行上述程序。

输出

0: string: 49


浙ICP备17015664号 浙公网安备 33011002012336号 联系我们 网站地图  
@2019 qikegu.com 版权所有,禁止转载