当前位置:网站首页>Why do programming languages ​​have the concept of variable types?

Why do programming languages ​​have the concept of variable types?

2022-08-11 00:01:00 cat under the pea

大家好,我是猫哥.There are some high quality on zhihu problem,比如这一个:

对于此问题,a millionVgave a high rating:

I wrote a lengthy introduction Python 动态类型&Strongly Typed Topics(点击阅读),两周前,还从 B Accident Analysis of Station Collapse,讨论了 Lua Hidden by weak typing bug 问题(点击阅读),analyzed earlier为什么 Python 没有 void 类型 .但是,On why programming languages ​​evolved“类型”、Why do variables need to have“类型”呢?

There are a lot of great answers to this question,Here to share with you,希望对你有所启发~~

作者:invalid s(PythonThe cat is authorized to reproduce)

来源:https://www.zhihu.com/question/425821639/answer/1536947755

因为……我们有一个梦想:If we casually mention computers, we know what to do、If there is any program that can automatically identify logic errors in the program,那该有多好啊!!!

实践中,whether you study math、Physics or something else,Numbers have types.

比如说,The angle between the two sides of the table is90度,这个90is of type,为了方便,我们记为90°.

然后,同样的,The width of the table is90厘米,这个90is a length type of data,记为90cm.

这两个90cannot be added directly.table side length90cm,Add table Angle90°,得个180——what the hell is this?

类似的,Some people make fun of elementary school math problems:The surface temperature of red stars is4000℃,The surface temperature of the blue star is9000℃,Ask what their temperatures add up to?

People who ask this question are mentally retarded.,对吧.“The surface temperatures of different stars add up”是没有意义的.

进一步的,Physics has a method called“量纲分析”,Simply put, let the unit of data also participate in the calculation,For example, the unit of acceleration is(米/秒²).

那么,When you sum up a physical formula,just do it first“量纲分析”:What is calculated on the left and right sides of the equal sign in the formula,Are the dimensions the same??Don't lose it,肯定错了!

类似的,Two items to do add and subtract?Are they the same dimension??不一样?What the hell do you add up to acceleration and velocity?.

What can pass dimensional analysis is not necessarily correct,But pass the dimensional analysis must be a mistake.

借助这个工具,We can spend as little as possible、Identify errors as quickly as possible,Avoid wasting more time.

类似的,在程序中,We can also use the type,Let the compiler help us troubleshoot.

比如,小张的生日是7月1日,Xiao Wang monthly salary¥12000;Programmer's brain pumping,write a formula:

int sum = zhang.birthday+wang.salary;

The compiler can immediately point out that this is an error:

错误,+Data type mismatch on both sides:datetime型数据和decimalcannot be executed between type data+操作.

不仅如此,We can also use the type,让编译器“心领神会”help us choose(dispatch)正确操作.

比如,We want to keep a work to xiao zhang,Raise for Xiao Wang100块钱薪水;If there is no type system,then you might have to write:

//zhang.CVpoints to a string area,If you want to continue writing to the end, you need to calculate the originalCV的长度
zhang.CV = strcpy(zhang.CV + strlen(zhang.CV), "10月1Received personal third-class merit.");

wang.salary += 100;

很麻烦,对吧.

但如果zhang.CV是一个string类型,那么就简单了:

zhang.CV += "10月1Received personal third-class merit."
wang.salary += 100;

编译器知道“字符串的+The operation is to piece together another string behind”,和 decimal increase in value is not the same thing;and we can forget about the underlying differences,都写成+=就行了,The compiler will automatically choose the correct implementation.

Does the program become simpler and faster to write??Is the memory burden of programmers also reduced??

If you participate in the organization's knowledge competition unit,In theory, you can know everything without saying anything,You can write hard on the exam paper、充分展示自己的才华……

But in reality,Time limit for answering questions,It's impossible to let you speak for a day alone;There is limited space left in the test paper,You are not allowed to talk at length——Some non-professionals will even come up with“There is too little blank space on the test paper to write the answer”such aircraft.So you can only leave words“我知道答案,But the place is too lowercase”……

计算机也一样:Our memory is not infinite,impossible to allow you to“性别”里面填写“12Before the age of men12old girl18female to male20male to female”……

咳咳,开个玩笑.实践中,很多时候,A byte is also a matter of life and death.For example, if you have to process tens of millions of pieces of information,If one byte per message compression,it might be able to be done in memory;but one more byte……

Out Of Memory,BOOM!

in a normal data structure,The age of a person is generallyunsigned char,A single-byte unsigned integer can be represented up to255,足够用了;如果你搞错了:

wang.age = wang.salary

The compiler will tell you,“薪水”使用的类型decimal太大,Can't be put into the unsigned single-byte integer used by age(提示你“operation may cause data overflow”).

不仅如此.

If integers or simple fixed-point numbers are represented entirely in binary,So astronomical(For example, there are thirty or forty zeros after ten.)、高精度小数(精确到小数点100位,但前90位都是0),Aren't these a waste of space??Of course should be based on scientific notation on single precision、double precision number.

再比如,binary is just numbers,英文字符、中文方块字,How do these said?

因此,We had to develop various coding schemes;The algorithms supported by different encoding schemes、具体的运算过程,肯定是不一样的.

比如,对应到CPUon integer instructions,就有“单字节加”“double-byte plus”“four-byte plus”“octet plus”乃至“There are number of symbols”和“无符号数加”和“addition of carry bits”和“add without carry”等等区别;甚至BCDThe integer represented by the code must also be appended with an addition after the addition operation.DAACommand completion adjustment(相应的,use for subtractionDAS指令调整)……

这些,It's all confusing.

This is just integer addition and subtraction.plus single precision、双精度浮点数,Plus four arithmetic operations and tangent and cotangent square root take logarithm, etc.……

See why no one programs in assembly anymore?

这些东西,type system,Let the compiler automatically arrange appropriate instructions、确保计算结果正确.

说白了,It was mentioned before dispatch(当然,There is also a type matching check).

过去,The type system of a programming language often consists only of“基本类型”的完整支持,Only limited support for user-defined data structures;Object Orientation revolutionized this:从此,Even user-defined data structures,也可以通过“晚绑定”在运行时dispatch了.

与之同时,Object-oriented programming also adds“接口检查”actions such as——你可以调用 Person.Run(),但调用Stone.Run()编译器就会报错.因为“Stone will not run”.

This thing continues to evolve,and strong typing、弱类型,动态类型、静态类型,以及“I don't care about your type,Only care if you can perform an operation”the duck type and so on.

但归根结底,The type system does two things:

1、Arrange the right action based on the type

2、Find some logical errors with the help of the type system

做为初学者、业余开发者,The type system can be a constraint on you,Because you really don't understand what it is for、Why are there so many types、What are the differences between these types.那么“无”type scripting languages ​​are very convenient for you.

但实际上,Even if the so-called“only one type of string”的TCLThe language also supports various data types.just where you can't see,This language automatically does the type conversion for you.

This implicit conversion is easier to form a lot“坑”.For example, Zhihu is often complained about JavaScript,even because of different data values,其加法、Judgment, etc. operations will have different results——想要用好它,You have to memorize these results,Or write an expression and check the authenticity online……呸,check online“Correct use of addition”.This is obviously too tiring.

对专业开发者,如前所述,The type system is an extremely important and sharp tool.

用好它,On the one hand can use it“automatic dispatch”简化程序,On the other hand can use again“类型检查”Automatic detection of many, many errors.

The more complex your program is、规模越大,The more important the type system becomes.

原网站

版权声明
本文为[cat under the pea]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/222/202208102331542599.html