Ch 02. 데이터 - 06 불리언형

2025. 3. 24. 22:14Programming Language/C++

반응형

자료 표현형은 bool 
기본적으로 1바이트임 

사용은 

bool b0 = 0 == 0; 
bool b1 = 0 < 1;
bool b2 = 0 > 1;

과 같이 사용이 가능하다.

출력해보면 

1
1
0

로 출력될 것이다.

 

true/false로 출력하려면 

cout에는 플래그를 세팅해줄 수 있는데 bool 타입을 그냥 정수가 아니라 bool 타입으로 보여주기 위해선 
ios_base에 있는 boolalpha 정적 상수를 사용해주면 된다

사용할때에는 std::ios_base::boolalpha를 setf안에 넣어서 사용해주면 된다.

#include <iostream>

int main()
{
	bool b0 = 0 == 0;
	bool b1 = 0 < 1;
	bool b2 = 0 > 1;

	// 그냥 정수로 출력되는 경우
	std::cout << b0 << std::endl;
	std::cout << b1 << std::endl;
	std::cout << b2 << std::endl;
	
	std::cout.setf(std::ios_base::boolalpha);

	// true/false로 출력 하도록 boolalpha 플래그를 넣은 경우
	std::cout << b0 << std::endl;
	std::cout << b1 << std::endl;
	std::cout << b2 << std::endl;
}

 

 

 

사실 이 친구들은 if 문 안에서 사용될때 보통 사용된다.

#include <iostream>

int main()
{
	bool b0 = 0 == 0;
	bool b1 = 0 < 1;
	bool b2 = 0 > 1;

	if (b0)
		std::cout << "b0일때 현재 코드가 보입니다" << std::endl;
	if (b1)
		std::cout << "b1일때 현재 코드가 보입니다" << std::endl;
	if (b2)
		std::cout << "b2일때 현재 코드가 보입니다" << std::endl;
}

 

 

추후에 flow control을 할때 자주 사용될것인데 boolean은 반복문, 조건식, 연산자등에 많이 사용된다.

 

int형에 bool 타입을 삽입 하는 경우 1 혹은 0으로 출력된다.

#include <iostream>

int main()
{
	int itrue = true;
	int ifalse = false;

	std::cout << itrue << std::endl;
	std::cout << ifalse << std::endl;

}

 

 

여기서 플래그를 boolalpha를 추가하더라도 

#include <iostream>

int main()
{
	int itrue = true;
	int ifalse = false;

	std::cout.setf(std::ios_base::boolalpha);

	std::cout << itrue << std::endl;
	std::cout << ifalse << std::endl;

}

 

타입 자체가 int 형이기 때문에 출력의 결과는 동일하게 1과 0이 나온다.

 

bool 타입의 변수에 0은 false 0이 아닌 값은 모두 true로 볼 수 있다.

#include <iostream>

int main()
{
	bool btrue1 = 100;
	bool btrue2 = -42;
	bool btrue3 = 0.23;
	bool bfalse = 0;

	std::cout << btrue1 << std::endl;
	std::cout << btrue2 << std::endl;
	std::cout << btrue3 << std::endl;
	std::cout << bfalse << std::endl;

}

 

 

플래그를 넣어서 출력해보면

#include <iostream>

int main()
{
	bool btrue1 = 100;
	bool btrue2 = -42;
	bool btrue3 = 0.23;
	bool bfalse = 0;

	std::cout.setf(std::ios_base::boolalpha);

	std::cout << btrue1 << std::endl;
	std::cout << btrue2 << std::endl;
	std::cout << btrue3 << std::endl;
	std::cout << bfalse << std::endl;

}

 

반응형