'참' 을 의미하는 true와 '거짓'을 의미하는 false
#define TRUE 1
#define FALSE 0
#include <iostream>
using namespace std;
int main(void)
{
int num = 10;
int i = 0;
cout << "true: " << true << endl;
cout << "false: " << false << endl;
while (true)
{
cout << i++ << ' ';
if (i > num)
break;
}
cout << endl;
cout << "sizeof 1: " << sizeof(1) << endl;
cout << "sizeof 0: " << sizeof(0) << endl;
cout << "sizeof true: " << sizeof(true) << endl;
cout << "sizeof false: " << sizeof(false) << endl;
return 0;
}
- 'true와 false는 각각 1과 0을 의미하는 키워드이다' 는 잘못된 오해이다
- 이 둘을 출력하거나 정수의 형태로 형 변환하는 경우에 각각 1과 0으로 변환되도록 정의되어 있을 뿐이다
- sizeof 로 출력해보면 알 수 있듯이 true와 false는 1바이트 크기의 데이터고
- 0과 1은 4바이트 크기의 데이터이므로 true나 false가 0과 1이 아니라는 것을 알 수 있다
자료형 bool
- true와 false를 가리켜 bool형 데이터라 한다
- 그리고 bool int, double과 마찬가지로 기본 자료형의 하나이기 때문에 다음과 같이 bool형 변수를 선언하는 것이 가능하다
bool isTrueOne = ture;
bool isTrueTwo = false;
#include <iostream>
using namespace std;
bool IsPositive(int num)
{
if (num <= 0)
return false; //숫자가 0보다 작으면
else
return true; //숫자가 0보다 크면
}
int main(void)
{
bool isPos;
int num;
cout << "Input number: ";
cin >> num;
isPos = IsPositive(num);
if (isPos == true)
cout << "Positive number" << endl; // isPos가 true면
else
cout << "Negative number" << endl; // isPos가 false면
return 0;
}
'C++ 이야기 (열혈) > C언어 기반의 C++ 2' 카테고리의 다른 글
6. C++에서 C언어의 표준함수 호출하기 (0) | 2023.01.17 |
---|---|
5. malloc & free를 대신하는 new & delete (0) | 2023.01.17 |
4. 참조자(Reference)와 함수 (0) | 2023.01.17 |
3. 참조자 &(Reference)의 이해 (0) | 2023.01.17 |
1. 시작에 앞서 (0) | 2023.01.17 |