C++布尔类型,三目运算符,new和delete详解
一、c++布尔类型
- bool的两种内建的常量
true(1)和 false(0)
表示状态。这三个名字都是关键字。 - 给 bool 类型赋值时,非 0 值会自动转换为 true(1),0 值会自动转换 false(0);
- bool 类型占 1 个字节大小 。
- C语言并没有彻底从语法上支持“真”和“假”,只是用 0 和非 0 来代表。
代码演示:
#include <iostream>
using namespace std;
void test01()
{
bool mybool;
cout<<sizeof(bool)<<endl;
mybool=false;
cout<<"false="<<false<<endl;
cout<<"true"<<true<<endl;
}
int main(int argc, char *argv[])
{
test01();
return 0;
}
任何数字值或指针值都可以被隐式转换为bool值。任何非零值都被转换为true,而零被转换成false:
bool a=-100;//true
bool b=0;//false
二、三目运算符a>b?a>b
1.c语言三目运算表达式返回值为数据值,为右值,不能赋值。
代码演示:
#include <iostream>
using namespace std;
int main()
{
int a=40;
int b=50;
printf("结果:%d\n",a>b?a:b)//50
//a>b?a:b整体结果为右值不能被赋值
//a>b?a:b=100;//error
}
2.c++经常用三目运算(?:)符取代if~else,通用·格式如下:
expression1?expression2:expression3
如果expression1
为true
,则表达式的值为expression2
,反之表达式值为expression3
.代码演示:
#include <iostream>
using namespace std;
int main()
{
int a,b;
cout<<"Enter a b:";
cin