Boolean
Boolean (bool) เป็นการแสดงผลการทำงานแบบลอจิกส์ จะมี 2 สถานะคือ true/false
void f(int a, int b)
{
bool b1{ a == b };
}
ตัวอย่างฟังก์ชั่นเปรียบเทียบค่า a กับ b ถ้า a ไม่เท่ากับ b ให้ b1 มีค่าเป็น false
ตัวอย่างการใช้ Boolean เป็นฟังก์ชั่นทดสอบเงื่อนไข
bool greater(int a, int b) { return a > b; }
by definition true จะมีค่า integer เป็น 1 และ false จะมีค่า integer เป็น 0 ในทางกลับกันสามารถ convert ได้เช่นกันคือถ้าค่า integer ไม่เท่ากับ 0 จะมีค่า Boolean เป็น true และ 0 จะเป็น false
bool b1 = 7; //7!=0 ดังนั้นให้ผลเท่ากับ true
bool b2{ 7 }; //error: narrowing conversion
int i1 = true;
int i2{ true };
cout << i1 << "\n"; //แสดงผลเป็น 1
cout << i2 << "\n"; //แสดงผลเป็น 1
Arithmetic and bitwise logic
bool a = true; bool b = true; bool y = a || b; cout << "a+b = " << a + b<<"\n"; //แสดงผลเท่ากับ 2 ในความหมายคือ true cout << "a-b = " << a - b << "\n"; //แสดงผลเท่ากับ 0 ในความหมายคือ false cout << "a||b = " << a || b ; //แสดงผลเท่ากับ 1 ในความหมายคือ true ค่าที่แสดง a+b = 2 a-b = 0 a||b = 1
pointer สามารถ convert เป็น bool ได้ โดย non-null pointer มีค่าเป็น true และ null pointer มีค่าเป็น false
void g(int* p)
{
bool b{ p != nullptr }; //ทดสอบ null pointer
cout << "b =" << b << "\n"; //แสดงค่า b
if (p) {
cout << "pointer is not null\n"; //ถ้า p ไม่เท่ากับ nullptr ให้แสดงค่านี้
}
}
int main()
{
int a1 = 5;
int* a = &a1;
//convert null poiter to boolean
g(NULL);
//convert not null poiter to boolean
g(a);
}
แสดงผล
b =0
b =1
pointer is not null
