Solidity 솔리디티 강좌 22강 : 반복문 (for, while, do-while)

flowing1ife·2023년 7월 7일
0

[ Solidity 깨부수기 ]

목록 보기
22/29
post-thumbnail

Solidity 솔리디티 강좌 22강 : 반복문 (for, while, do-while)
이번엔 solidity의 반복문에 대해 알아보도록 하자.


반복문

📌 Solidity

반복문도 마찬가지로 다른 프로그래밍 언어와 같다고 해도 무방하다. for, while, do-while이 있다.

solidity 내에는 public, private, external, internal, 이렇게 총 4가지의 접근 제한자가 존재한다.

// SPDX-License-Identifier: GPL-3.0
pragma solidity >= 0.7.0 < 0.9.0;

contract lec22 {
    event CountryIndexName(uint256 indexed _index, string _name);
    string[] private countryList = ["South Korea", "North Korea", "USA", "China","Japan"];

    function forLoopEvents()public {
        for(uint256 i = 0; i < countryList.length; i++){
            emit CountryIndexName(i, countryList[i]);
        }
    }
}

CountryIndexName event는 _index, _name을 출력한다. forLoopEvents 함수는 CountryIndexName event를 반복하여 실행해 countryList 배열의 값을 출력한다.

👉 결과

다음과 같이 index가 1씩 증가하며 index에 해당하는 countryList 배열의 값을 출력하는 것을 알 수 있다.

// SPDX-License-Identifier: GPL-3.0
pragma solidity >= 0.7.0 < 0.9.0;

contract lec22 {
    event CountryIndexName(uint256 indexed _index, string _name);
    string[] private countryList = ["South Korea", "North Korea", "USA", "China","Japan"];

    function forLoopEvents()public {
        for(uint256 i = 0; i < countryList.length; i++){
            emit CountryIndexName(i, countryList[i]);
        }
    }

    function whileLoopEvents() public {
        uint256 i = 0;
        while(i < countryList.length){
            emit CountryIndexName(i, countryList[i]);
            i++;
        }
    }

//조건을 나중에 check하니 조건에 맞지 않음에도 실행을 해버림 
    function doWhileLoopEvents() public {
        uint256 i = 0;
        do{
            emit CountryIndexName(i, countryList[i]);
            i++;
        }
        while(i < countryList.length);
    }

}

for문으로 구현된 forLoopEvents 함수를 각각 while문과 do-while문으로도 구현을 해보았다.


👉 결과

whileLoopEvents 함수 호출 결과이다.

doWhileLoopEvents 함수 호출 결과이다.


출처 및 참고 자료

profile
👩🏻‍💻 Backend Engineer, Contract Developer

0개의 댓글