Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

문타쿠, 공부하다.

[C언어 코딩 도장] Unit 22. 불 자료형 사용하기 본문

C언어/C언어 코딩 도장

[C언어 코딩 도장] Unit 22. 불 자료형 사용하기

개발새발 문타쿠 2023. 8. 28. 21:17

INTRO

"불(boolean) 자료형"

  • 논리 자료형이라고도 하며 참과 거짓을 나타낸다.
  • stdbool.h 헤더 파일을 사용하면 true를 참으로, false를 거짓으로 나타낼 수 있다.

22.1 stdbool.h 헤더 파일 사용하기

#include <stdio.h>
#include <stdbool.h>

int main(void)
{
	bool b1 = true;

	if (b1 == true)
		printf("참\n");
	else
		printf("거짓\n");
	
	return 0;
}

22.2 불 자료형 크기 알아보기

#include <stdio.h>
#include <stdbool.h>

int main(void)
{
	printf("bool의 크기: %zd\n", sizeof(bool));
	
	return 0;
}
  • bool의 크기는 1바이트

22.3 불 자료형과 논리 연산자 사용하기

#include <stdio.h>
#include <stdbool.h>

int main(void)
{
	printf("%d\n", false && false);
	printf("%d\n", false && true);
	printf("%d\n", true && false);
	printf("%d\n\n", true && true);

	printf("%d\n", false || false);
	printf("%d\n", false || true);
	printf("%d\n", true || false);
	printf("%d\n", true || true);
	
	return 0;
}

22.4 true, false를 문자열로 출력하기

#include <stdio.h>
#include <stdbool.h>

int main(void)
{
	bool b1 = true;
	bool b2 = false;

	printf(b1 ? "true" : "false");
	printf("\n");
	printf(b2 ? "true" : "false");
	printf("\n");

	printf("%s\n", b1 ? "true" : "false");
	printf("%s\n", b2 ? "true" : "false");

	return 0;
}


22.5 if 조건문에서 불 자료형 사용하기

#include <stdio.h>
#include <stdbool.h>

int main(void)
{
	if (true)
		printf("참\n");
	else
		printf("거짓\n");

	if (false)
		printf("참\n");
	else
		printf("거짓\n");

	return 0;
}