Bool Type
Kiểu bool có mục đích lưu trữ các giá trị logic true
hoặc false
, biểu diễn dạng số của chúng lần lượt là 1
hoặc 0
.
VD:
cpp
bool a = true;
bool b = false;
bool c = 1;
1
2
3
2
3
Biểu diễn bên trong là một số nguyên lớn 1 byte. Cần lưu ý rằng trong các biểu thức logic, bạn có thể sử dụng các kiểu số nguyên hoặc số thực khác hoặc các biểu thức thuộc các kiểu này - trình biên dịch sẽ không tạo ra bất kỳ lỗi nào. Trong trường hợp này, giá trị 0
sẽ được hiểu là false
và tất cả các giá trị khác - là true
.
VD:
cpp
int i=5;
double d=-2.5;
if(i) Print("i = ",i," and is set to true");
else Print("i = ",i," and is set to false");
if(d) Print("d = ",d," and has the true value");
else Print("d = ",d," and has the false value");
i=0;
if(i) Print("i = ",i," and has the true value");
else Print("i = ",i," and has the false value");
d=0.0;
if(d) Print("d = ",d," and has the true value");
else Print("d = ",d," and has the false value");
//--- Kết quả thực thi
// i= 5 and has the true value
// d= -2.5 and has the true value
// i= 0 and has the false value
// d= 0 and has the false value
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21