[Solidity] 제어문

Alexandria·2024년 3월 4일

Solidity

목록 보기
7/11
post-thumbnail

1. If

조건문은 다음과 같이 사용할 수 있다.

contract HelloWorld {
    function testFunction(uint x) public pure returns (string memory) {
        if (x == 1) {
            return "x is not 1";
        } else if (x == 2) {
            return "x is not 2";
        } else if (x == 3) {
            return "x is not 3";
        } else {
            return "x is not 1,2,3";
        }
    }
}

2. 반복문

while 문은 다음과 같이 do...while이나 while 단독으로 사용할 수 있다.

contract HelloWorld {
    function myWhile(uint x) public pure returns (uint) {
        while (x != 0) {
            x -= 1;
        }
        return x;
    }

    function myDoWhile(uint x) public pure returns (uint) {
        do {
            x -= 1;
        }
        while (x != 0);
        return x;
    }
}

for 문도 다른 언어와 마찬가지로 사용된다.

contract HelloWorld {
    function testFunction(uint x) public pure returns (uint) {
        uint j;
        for (j = 0; j <= x; j ++) {
            if (j == x) break;
        }
        return j;
    }
}
profile
IT 도서관

0개의 댓글