本篇开始讲C++中的57个入门知识。
C语言中本质上是没有bool类型变量的,而在C++中bool类型变量是用来判断条件是否为真。
1. C语言中实现条件判断BOOL
- 有如下代码:
#include <iostream>
#include <string>
int main() {
//布尔类型 真 假
//条件判断 /逻辑类型
int n = 5;
int bRet = (n<=3);
if (bRet) {
printf("%s", "n>3");
}
else {
printf("n<3");
}
return 0;
}
F10
进行单步调试,由于n=5
是不小于3
的,条件不成立,因此bRest返回值为0
。
- 对代码进行修改,使得条件成立:
#include <iostream>
#include <string>
int main() {
//布尔类型 真 假
//条件判断 /逻辑类型
int n = 5;
int bRet = (n>3);
if (bRet) {
printf("%s", "n>3");
}
else {
printf("n<3");
}
return 0;
}
F10
进行单步调试,由于n=5
是大于3
的,条件成立,因此bRest返回值为1
。
由于C语言中是没有bool类型的,需要做如下操作:
typedef
是声明别名的关键字,我们可以使用typedef,为类型起别名。新别名的效果与原类型名效果一样。
基本语法是: typedef <原类型名> <新别名>
具体可参考:C语言基础入门48篇_38_函数指针与typedef(函数指针即指向函数的指针、函数指针定义int (*pfn)(int)、typedef给数据类型起别名,起到的作用一致、typedef简化函数指针)
#include <iostream>
#include <string>
//typedef声明int的别名为BOOL
typedef int BOOL;
int main() {
//布尔类型 真 假
//条件判断 /逻辑类型
int n = 5;
BOOL bRet = (n>3);
if (bRet) {
printf("%s", "n>3");
}
else {
printf("n<3");
}
return 0;
}
运行结果:与上面的结果一致
2. C++中的新类型bool
上述C语言中的int类型可以为0/1/非0非1,但实际的逻辑值只可能有真假两种情况,因此C++中将逻辑类型单独提出使用
bool
。
上述代码使用C++中的bool
类型
#include <iostream>
#include <string>
//typedef声明int的别名为BOOL
typedef int BOOL;
int main() {
//布尔类型 真 假 bool
//条件判断 /逻辑类型
int n = 5;
bool bRet = (n>3);
if (bRet) {
printf("%s", "n>3");
}
else {
printf("n<3");
}
return 0;
}
运行结果如下:返回为bool类型的true
3. bool和BOOL的区别
那么
bool
和
BOOL
的区别是在哪里呢?
BOOL
的本质是Int类型,除了0/1之外,还有可能是其他值,
bool
是什么样的呢?可以通过内存去看。
代码如下:
#include <iostream>
#include <string>
//typedef声明int的别名为BOOL
typedef int BOOL;
int main() {
//布尔类型 真 假 bool
//条件判断 /逻辑类型
int n = 5;
bool bRet = (n>3);
void* p = (void*)&bRet;
int nboolSize = sizeof(bool);
int nBOOLSize = sizeof(BOOL);
if (bRet) {
printf("%s", "n>3");
}
else {
printf("n<3");
}
return 0;
}
运行结果:看到bool
只占用一个字节,0为假非0为真
4. 任意指针类型的强制转换
代码中void* p = (void*)&bRet;
使用了指针的强制转换,之所以采用void*
类型指针,是因为任何指针类型都可以转为void
,void
转其他类型是需要强转的,在无法提前知道bool
返回的数据类型,先返回一个void*
类型,自行根据需求进行强转。
参考地址:
C语言基础入门48篇_35_指向同一个地址的指针的内涵(“(TYPE) 变量“实现强制转换、n = (int)m、指针作为存储地址的变量,有2个内涵:指向哪里和按照指针的类型进行数据解释)
C语言基础入门48篇_46_malloc与free(malloc申请堆返回void要指针强转、free释放堆,只需堆内存首地址、malloc配合sizeof增加可读性、注意出{}作用域导致无法释放)
5. bool类型的使用
在使用bool类型时,避免使用
if(bRet==false)
,这是因为bool本身就是条件表达式的结果
6. 学习视频地址:bool变量类型
更多推荐
C++57个入门知识点_01_ bool变量类型(判断条件是否为真、C语言实现方法BOOL、typedef使用、bool和BOOL的区别、任意指针类型的强制转换
发布评论