Programing/C++

[C++ 프로그래밍] 불리언 (Boolean) 타입

유니얼 2024. 6. 21. 00:53
728x90

C++ 기초 프로그래밍: 불리언 (Boolean) 타입

C++ 프로그래밍에서 불리언(Boolean) 타입은 논리적인 참(true)과 거짓(false)을 나타내는 데 사용됩니다. 불리언 타입은 조건문, 반복문, 논리 연산 등 다양한 프로그래밍 요소에서 핵심적인 역할을 합니다. 이번 블로그 글에서는 C++에서 불리언 타입을 사용하는 방법과 그 특성에 대해 알아보겠습니다.

불리언 타입 선언과 초기화

C++에서 불리언 타입은 bool 키워드를 사용하여 선언하며, true 또는 false 값을 가집니다. 다음 예제는 불리언 변수를 선언하고 초기화하는 방법을 보여줍니다.

#include <iostream>

int main() {
    bool red_light {false};
    bool green_light {true};
}

조건문에서의 불리언 사용

불리언 타입은 조건문에서 매우 유용하게 사용됩니다. 다음은 불리언 변수를 사용한 조건문의 예제입니다:

if (red_light == true) {
    std::cout << "Stop!" << std::endl;
} else {
    std::cout << "Go through!" << std::endl;
}

if (green_light) {
    std::cout << "The light is green!" << std::endl;
} else {
    std::cout << "The light is NOT green!" << std::endl;
}

위 예제에서 red_light가 false이기 때문에 "Go through!"가 출력되고, green_light가 true이기 때문에 "The light is green!"이 출력됩니다.

불리언 타입의 크기

C++에서 bool 타입의 크기는 일반적으로 1바이트입니다. sizeof 연산자를 사용하여 불리언 타입의 크기를 확인할 수 있습니다.

std::cout << "sizeof(bool) : " << sizeof(bool) << std::endl;

불리언 값 출력

불리언 값을 출력할 때, 기본적으로 true는 1로, false는 0으로 출력됩니다. std::cout 스트림의 boolalpha 조작자를 사용하면 true와 false를 텍스트 형태로 출력할 수 있습니다.

std::cout << std::boolalpha;
std::cout << "red_light : " << red_light << std::endl;
std::cout << "green_light : " << green_light << std::endl;

예제코드

#include <iostream>

int main()
{
    bool red_light{false};
    bool green_light{true};

    if (red_light == true)
    {
        std::cout << "Stop!" << std::endl;
    }
    else
    {
        std::cout << "Go through!" << std::endl;
    }

    if (green_light)
    {
        std::cout << "The light is green!" << std::endl;
    }
    else
    {
        std::cout << "The light is NOT green!" << std::endl;
    }

    // sizeof() 연산자를 사용한 크기 출력
    std::cout << "sizeof(bool) : " << sizeof(bool) << std::endl;

    // 불리언 값 출력
    // 1은 true를, 0은 false를 나타냅니다.
    std::cout << std::endl;
    std::cout << "red_light : " << red_light << std::endl;
    std::cout << "green_light : " << green_light << std::endl;

    // boolalpha를 사용하여 불리언 값을 true/false로 출력
    std::cout << std::boolalpha;
    std::cout << "red_light : " << red_light << std::endl;
    std::cout << "green_light : " << green_light << std::endl;

    // Go through!
    // The light is green!
    // sizeof(bool) : 1

    // red_light : 0
    // green_light : 1
    // red_light : false
    // green_light : true

    return 0;
}

출력 결과

위 코드를 실행하면 다음과 같은 결과를 얻을 수 있습니다:

Go through!
The light is green!
sizeof(bool) : 1

red_light : 0
green_light : 1
red_light : false
green_light : true

결론

C++에서 불리언 타입은 논리적인 조건을 처리하고 제어 흐름을 관리하는 데 필수적인 역할을 합니다. 불리언 변수를 선언하고 사용하는 방법을 이해하면 조건문, 반복문, 논리 연산 등을 효과적으로 활용할 수 있습니다.

반응형