Solidity 솔리디티 강좌 22강 : 반복문 (for, while, do-while)
이번엔 solidity의 반복문 중 continue, break 개념에 대해 알아보도록 하자.
continue와 break 개념도 다른 프로그래밍 언어와 같다고 보아도 무방하다.
// SPDX-License-Identifier: GPL-3.0
pragma solidity >= 0.7.0 < 0.9.0;
contract lec23{
event CountryIndexName(uint256 indexed _index, string _name);
string[] private countryList = ["South Korea", "North Korea", "USA", "China","Japan"];
function useContinue()public {
for(uint256 i = 0; i < countryList.length; i++){
if(i%2 == 1){ //홀수
continue;
}
emit CountryIndexName(i, countryList[i]);
}
}
}
useContinue
함수는 반복문을 돌며 i
가 짝수일 때만 CountryIndexName
event를 실행하는 함수이다.
👉 결과
이처럼 i
가 0, 2, 4일 때만 CountryIndexName
event가 실행되었다.
// SPDX-License-Identifier: GPL-3.0
pragma solidity >= 0.7.0 < 0.9.0;
contract lec23{
event CountryIndexName(uint256 indexed _index, string _name);
string[] private countryList = ["South Korea", "North Korea", "USA", "China","Japan"];
function useContinue()public {
for(uint256 i = 0; i < countryList.length; i++){
if(i%2 == 1){
continue;
}
emit CountryIndexName(i, countryList[i]);
}
}
function useBreak()public {
for(uint256 i = 0; i < countryList.length; i++){
if(i == 2){
break;
}
emit CountryIndexName(i, countryList[i]);
}
}
}
useBreak
함수는 반복문을 돌며 i
가 2일 때 반복문을 벗어나는 함수이다.
👉 결과
이처럼 i
가 0, 1 일 때까지는 CountryIndexName
event가 실행되고 그 이후로는 반복문을 빠져나왔다.
출처 및 참고 자료