C++ 제어문의 초기화 구문 (init-statement)

Seongcheol Jeon·2024년 12월 7일
0

CPP

목록 보기
33/47
post-thumbnail

ifswitch, for 같은 제어문에서 사용할 변수를 제어문 외부에서 초기화하면 코드를 읽을 때 혼란스러울 수 있다. 이를 보완하는 문법이 바로 초기화 구문(init-statement)이다.

예를 들어 다음 코드에서는 element 변수를 if문 외부에서 함수가 반환하는 값으로 초기화한 후 if문의 조건식과 for문에서 특정 인덱스의 원소값을 연산할 때 사용한다.

int element = get_confition_value();
if(0 != element) {
	for(auto i = 0; i < 10; i++) {
    	cout << element + i << endl;
    }
}

분기문 근처에 element 변수를 초기화하는 코드가 있지만, 이후에 코드가 추가된다면 분기문과 멀어질 수 있다. 그러면 분기문의 의미를 파악하기가 어려워진다. 또한 변수값이 의도치 않게 변경되어 오류가 발생할 수도 있다.

분기문에 초기화 구문을 이용하면 이러한 문제를 해결할 수 있다. 분기문에서 사용할 변수의 초기화를 분기문 안에 명시함으로써 분기문과 초기화 구문의 관계를 분명히 할 수 있으며, 해당 변수의 범위도 분기문으로 한정할 수 있다.

다음은 ifswitch 그리고 범위 기반 for문에 초기화 구문을 사용한 예이다. 제어문에 초기화 구문이 들어옴으로써 element 변수의 의미를 쉽게 파악할 수 있게 되었다. 예에서는 초기화 구문을 간단하게 작성했지만 람다 등 조금 더 복잡한 표현식을 사용할 수도 있다.

#include <iostream>
#include <array>
#include <algorithm>

using std::cout;
using std::endl;

enum class parity : int {
    even = 0,
    odd
};


int main()
{
    std::array<int, 5> data_array{ 55, 33, 27, 39, 10 };

    // if 문에 초기화 구문 사용
    if (auto element = data_array[3] + data_array[4]; element > 20) {
        cout << "element is greater than 20" << endl;
    }
    else {
        cout << "element is less than or equal to 20" << endl;
    }

    // switch 문에 초기화 구문 사용
    switch (auto element = static_cast<parity>(data_array[4] % 2); element) {
    case parity::odd:
        cout << "element is odd" << endl;
        break;
    case parity::even:
        cout << "element is even" << endl;
        break;
    }

    // 범위 기반 for문에 초기화 구문 사용
    for (std::sort(data_array.begin(), data_array.end()); auto&& element : data_array){
        cout << element << ", ";
    }


    return 0;
}

실행 결과

element is greater than 20
element is even
10, 27, 33, 39, 55,

제어문에서 조건식 앞에 초기화 구문을 작성하고 세미콜론(;)을 추가한다. 초기화 구문은 선택 사항이므로 생략할 수 있다. ifswitch 문의 초기화 구문은 C++17에서 추가되었으며, 범위 기반 for문의 초기화 구문은 C++20에서 추가되었다.

0개의 댓글