当前位置:网站首页>How do different types of variables compare with zero
How do different types of variables compare with zero
2022-06-30 12:18:00 【Desperate Azi】
Most of what we see are integers and 0 Compare
It's rare to see bool The type and 0 Compare
float The type and 0 Compare
Pointer type and 0 Compare
So this issue Violet Lead us to learn together
Catalog
1、 What is an expression 、 What is a sentence
2. Judgment statement How is it implemented
3.bool Variables and " Zero value " Compare
3.1 C Is there any in the language bool type ?
3.2 bool Variables of type occupy several bytes ?
3.3 bool Value and 0 Compare how to compare ?
4.float Variables and " Zero value " Compare
4.1 Whether two floating-point numbers can be compared equally
4.2 So how do two floating point numbers compare ?
4.3 float Variables and 0 Compare
5. Pointer variables and “ Zero value ” Compare
5.2 Pointer variable is compared with zero
6.else With which if What about pairing ?
1、 What is an expression 、 What is a sentence
1.1 What is an expression
- C In language , Use all kinds of The operator hold Variable Connect , Form a meaningful formula , It's called expression . for example :a = b + c
1.2 What is a sentence
- Add a after the expression A semicolon , There is a sentence . for example :a = b + c;
- Of course, it's not just statements with semicolons after expressions , There are also similar to Input Output Function call wait sentence . for example :scanf("%d",&a); printf("%d",a); add(a,b);
- only one A semicolon ; It's called. Empty statement
- C In language , Use a pair of braces {} The enclosed Multiple statements be called Compound statement , Compound statement Grammatically considered to be A sentence
notes : Just remember that the sentence ends with a semicolon , Except for compound statements
2. Judgment statement How is it implemented
1.1 if

First, execute expression , The value of the expression is really Just perform if Inside sentence , by false be Don't execute
1.2 Single branch

First, execute the expression , The value of the expression is really Just perform if Inside sentence 1, by false be perform else Inside sentence 2
1.3 Multiple branches

First judgement expression 1, expression 1 The value of is really Just perform if Inside sentence 1, by false Then judge else if Inside expression 2, expression 2 The value of is really execute else if Inside sentence 2, by false execute else Inside sentence 3
1.4 nesting

First judgement expression 1, expression 1 The value of is really Just perform if Inside sentence 1 then Judge Inside expression x , if expression x by really be Execute statement x, expression x by False execution statement y . expression 1 by false Then judge else if Inside expression 2, expression 2 The value of is really execute else if Inside sentence 2, expression 2 by false execute else Inside sentence 3
Conclusion :
- if Statement execution , First execute the value of the completion expression , Get logical results , In making a judgment
- C in 0 Said the false , Not 0 Said really
3.bool Variables and " Zero value " Compare
3.1 C Is there any in the language bool type ?
reflection :C Is there any in the language bool type ?
answer :c99 Not before bool type , Mainly c90 No, . but c99 Introduced _Bool type (_Bool Is a type , But in the new header file stdbool.h in , It was written again as bool, In order to ensure C/C++ Compatibility ).

bool Is a true and false type :true It's true ,false For false
3.2 bool Variables of type occupy several bytes ?

In the test above , We can see that bool Variables of type account for A byte .

My little friend may be confused when he sees this , Why is it capitalized BOOL 、TRUE It can also run , And its size is four bytes ? Let's turn to its definition

Now we know why capital letters BOOL Variables of type account for Four bytes 了 , Because in the source code , That's the definition :typedef int BOOL;
notes : This is all Microsoft I made it myself BOOL value . stay vs Transfer to BOOL Corresponding header file , Turn to the top , You can see Microsoft's copyright information . Use BOOL Need to add #include<windows.h> The header file .
We generally write code not only on the platform we use , It also needs to be available on other platforms , So this involves Cross platform , and Microsoft Defined Exclusive type , Other platforms I won't support it , So it's just Unsupported use
summary :
- priority of use c90, It's the way we've been using before and after ( although c90 Does not support bool type , But it can express true and false by integer ,0 For false 、 Not 0 It's true )
- In case you have to use bool, recommend c99 standard , Not recommended MS Customize .
3.3 bool Value and 0 Compare how to compare ?
#include<stdio.h>
#include<stdbool.h>
int main()
{
bool a = true;
if (1 == a)
{
printf("1\n");
}
if (true == a)
{
printf("2\n");
}
if (a)// recommend
{
printf("3\n");
}
return 0;
}Why do you recommend No 3 individual if How to write ?
answer : a Itself is a bool Type value , Is it true or false .
Conclusion :bool type , Direct determination , Compare with specific values without operators
4.float Variables and " Zero value " Compare
We know that floating point numbers are stored in memory , There may be a Loss of accuracy ( notes : The loss here , Not blindly reduced , There may be more , When the floating-point number itself is stored , When the calculations are endless , Meeting “ rounding ” Or other Strategy )

4.1 Whether two floating-point numbers can be compared equally
As you can see from the following image code x=1.0,y=0.1, So for if Expression judgment x - 0.9 It should be equal to 0.1 ,0.1 And y Equality should be printed 1, But it printed 0 , That's why ?

So let's go on , Let's look at printing x-0.9 and 0.1 What exactly is printed ?
In the original memory x - 0.9 Is not the same as 0.1, It's a loss of accuracy , and y Neither 0.1, The accuracy is also lost , So the code above is not printed 1

Conclusion : Because of the loss of accuracy , Two floating-point numbers , Never use == Make an equality comparison
4.2 So how do two floating point numbers compare ?
A range accuracy comparison should be made

notes :fabs Is the absolute value of a floating-point number
How to set precision ?
- Define your own macro settings
- Use system accuracy
1. Use the macro definition to set the precision

2. Use system accuracy

4.3 float Variables and 0 Compare
#include<stdio.h>
#include<float.h>
#include<math.h>
int main()
{
float x = 0.000000000000001f;// When the value is small enough , Will be judged as 0
//if (fabs(x) < DBL_EPSILON)
if (fabs(x-0) < DBL_EPSILON)
{
printf("1\n");
}
else
{
printf("0\n");
}
return 0;
}5. Pointer variables and “ Zero value ” Compare
5.1 Express 0 Methods
We've studied before Numbers 0、 Escape character \0、 empty NULL, They can also mean 0

We can go to NULL Definition , You can see that in fact NULL Namely 0

5.2 Pointer variable is compared with zero

6.else With which if What about pairing ?
1. This code always makes people feel like it's different from the first one if matching , In fact, it is similar to the second one if matching , because else The principle of proximity is adopted , So this code doesn't print anything
#include<stdio.h>
int main()
{
int x = 0;
int y = 1;
if (10 == x)
if (11 == y)
printf("hi\n");
else
printf("hello\n");
return 0;
}2. This is the right code style , It's easy to see else With which if matching
#include<stdio.h>
int main()
{
int x = 0;
int y = 1;
if (10 == x)
{
if (11 == y)
{
printf("hi\n");
}
}
else
{
printf("hello\n");
}
return 0;
}Why? Not written x==10, The written 10 == x?
answer : Because writing in this way can avoid == It's written in =, If you write it carelessly =, We know that the left side of the assignment number must be a variable , So this is a grammatical error , The compiler prompts , If it is written carelessly x = 10, This is a running error. The system will not prompt .
This shows how important a good programming style is to programmers , Develop good programming habits , From you and me .
边栏推荐
- NoSQL——Redis的配置与优化
- 串行通信接口8250
- Go zero micro Service Practice Series (VIII. How to handle tens of thousands of order requests per second)
- Flutter 从零开始 006 单选开关和复选框
- 使用Power Designer工具构建数据库模型
- 移除无效的括号[用数组模拟栈]
- Conference Preview - Huawei 2012 lab global software technology summit - European session
- Redis - ziplist compressed list
- R language ggplot2 visualization: use ggplot2 to visualize the scatter diagram, and_ Set the alpha parameter in the point parameter to specify the transparency level of data points (points transparent
- R语言ggplot2可视化:使用ggplot2可视化散点图、使用scale_size函数配置数据点的大小的(size)度量调整的范围
猜你喜欢

这些电影中的科幻构想,已经用AI实现了

AGCO AI frontier promotion (6.30)

智慧法院新征程,无纸化办公,护航智慧法院绿色庭审

Use of redis in projects

不同类型的变量与零究竟是如何比较

海思3559开发常识储备:相关名词全解

Embedded sig | multi OS hybrid deployment framework

MySQL 表的内连和外连

After the node is installed in the NVM, the display is not internal or external when the NPM instruction is used

Map集合
随机推荐
R language ggplot2 visualization: use ggplot2 to visualize the scatter diagram and use scale_ The size function configures the measurement adjustment range of the size of the data point
YOLOv5导出onnx遇到的坑
海思3559萬能平臺搭建:獲取數據幀修改後編碼
A Generic Deep-Learning-Based Approach for Automated Surface Inspection-論文閱讀筆記
Ensemble de cartes
Hannaiping of Qilin software: the construction of Digital China needs its own open source root community
Use of redis in projects
MySQL 表的内连和外连
3D视觉检测在生产流水的应用有哪些
beego开发博客系统学习(二)
R语言ggplot2可视化:使用ggplot2可视化散点图、aes函数中的size参数指定数据点的大小(point size)
[cloud native | kubernetes] in depth understanding of deployment (VIII)
200. 岛屿数量
[cf] 803 div2 B. Rising Sand
麒麟软件韩乃平:数字中国建设需要自己的开源根社区
治数如治水,数据治理和数据创新难在哪?
剑指 Offer 05. 替换空格: 把字符串 s 中的每个空格替换成“%20“
Flutter 从零开始 007 输入框
AGCO AI frontier promotion (6.30)
A High-Precision Positioning Approach for Catenary Support Components With Multiscale Difference阅读笔记