Solidity break 与 continue

Solidity 循环语句支持 continue 和 break,用来改变循环流程。

  • continue – 跳出本次循环,继续执行下一次循环
  • break – 跳出循环,不再执行当前循环

1. break 示例

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract SolidityTest {
   uint storedData; 
   
   constructor() {
      storedData = 10;   
   }
   
   function getResult() public pure 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);
   }
}

运行上述程序,输出结果:

0: string: 3

2. continue 示例

// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;

contract SolidityTest {
   uint storedData; 
   constructor() {
      storedData = 10;   
   }
   function getResult() public pure 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);
   }
}

运行上述程序,输出结果:

0: string: 49

下一章:Solidity 字符串

Solidity 中,字符串值使用双引号(")和单引号(')包括,字符串类型用 string 表示。字符串是特殊的数组,是引用类型。// SPDX-License-Identifier: MITpragma sol ...