Block-Chain/Solidity

조건문 & 반복문

WebDevLee 2023. 2. 15. 14:21

Solidity의 조건문과 반복문에 대해 정리하였습니다.

 

 


< if 조건문 >

Solidity에도 다른 언어와 마찬가지로 조건문이 있습니다.

문법은 JavaScript와 동일합니다.

 

  • 조건문 형식
if(if가 발동 되는 조건){
    if 내용 
}
else if(else if가 발동 되는 조건){
    else if 내용 
}
...
else{ if, else if 가 발동이 안되면
    else 내용 
}

 

Ex)

string private result = "";
function isIt5or3or1(uint256 _number) public returns(string memory){
    if(_number == 5){
        result = "Yes, it is 5";
        return result;
    }
    else if(_number == 3){
        result = "Yes, it is 3";
        return result;
    }
    else if(_number == 1){
        result = "Yes, it is 1";
        return result;
    }
    else{
        result = "No, it is not 5, 3 or 1";
        return result;
    }

 

 


< loop 반복문 >

반복문의 종류는 총 3가지가 있습니다.
for
while
do-while

문법은 JavaScript와 동일합니다.

 

  • for 반복문
for (초기값; 값이 얼마나 forloop을 돌아야하는지; forloop 한번 돌때마다 값의 변화;) {
  loop 내용;
}
  • while 반복문
초기값
while (값이 얼마나 forloop을 돌아야하는지) {
  loop 내용;
}
  • do-while 반복문
초기값
do{
  loop 내용;
}
while (값이 얼마나 forloop을 돌아야하는지)

 

 


< continue, break >

continue와 break 키워드는 끝나지 않은 반복문의 제어를 위해 사용합니다.

 

  • continue : 다음 반복문으로 이동
  • break : 반복문을 끝냄

 

Ex)

contract lecture23 {
  event CountryIndexName(uint256 indexed _index, string _name);
  string[] private countryList = ["South Korea", "North Korea", "USA", "China", "Japan"];
  
  funtion useContinue() public {
    for (uint256 i = 0; i < countryList.length; i++) {
      if (i%2 == 1) {
        continue;
      }
      emit CountryIndexName(i, countryList[i]);
    }
  }
  
  funtion useBreak() public {
    for (uint256 i = 0; i < countryList.length; i++) {
      if (i == 3) {
        break;
      }
      emit CountryIndexName(i, countryList[i]);
    }
  }
}

 

 


< linear search >

배열의 값을 검색할 때 자주 사용하는 linear search 사용방법에 대해 소개합니다.

 

Ex)

string[] private countryList = ["South Korea", "North Korea", "USA", "China", "Japan"];

function linearSearch(string memory _search) public view returns(int256, string memory) {
  for (uint256 i = 0; i < countryList.length; i++) {
    if (keccak256(bytes(countryList[i]) == keccak256(bytes(_search)) {
      return (i, countryList[i]);
    }
  }
  return (99, "Nothing");
}

: 솔리디티 내에서 string은 직접 비교가 불가능해, 다음과 같은 과정을 거친 후 비교해줘야 함.

1. string을 bytes

2. keccak256을 이용해 다시 해시화