简体   繁体   English

为什么我们需要在赋值之前指定变量的数据类型?

[英]Why do we need to specify the data type of variable before assigning a value?

Let's say we want to define a variable that stores the age of a certain individual;假设我们要定义一个变量来存储某个人的年龄;

int main(void) {
 int age=5;
 printf(“%d\n”,age);
}

Here, before assigning the variable, we specify the type of data it would store.在这里,在分配变量之前,我们指定它将存储的数据类型。 Does we define it just to tell the compiler/interpreter how many bytes the value will occupy in memory.我们是否定义它只是为了告诉编译器/解释器该值将在 memory 中占用多少字节。 No other reason?没有其他原因?

Variables usually change their value (that's why they are called variables).变量通常会改变它们的值(这就是它们被称为变量的原因)。 The initial value of a variable usually doesn't say much about how the variable is used, and what it's for.变量的初始值通常不会过多地说明该变量是如何使用的,以及它的用途。

If you want to implement an algorithm which calculates an average age, you might need your variable which holds the age to be non-integer, like float or double .如果您想实现一个计算平均年龄的算法,您可能需要将年龄保持为非整数的变量,例如floatdouble You usually want to initialize it to 0, which is an integer, so the compiler can't come up with a correct suggestion for its type.您通常希望将其初始化为 0,即 integer,因此编译器无法为其类型提供正确的建议。

int main(void)
{
    int age=5;
    printf("%d\n",age);
    // Now print the age in decades (units of 10 years)
    printf("%d\n", age / 10); // prints 0 - incorrect answer

    double correct_age = 5;
    printf("%f\n", correct_age);
    // Now print the age in decades (units of 10 years)
    printf("%f\n", correct_age / 10); // prints 0.5 - correct answer
}

C++ has support for type inference: auto age = 5 declares age as an integer, while auto age = 5.0 declares it as double . C++ 支持类型推断: auto age = 5将 age 声明为 integer,而auto age = 5.0将其声明为double This support was not deemed important when C was created, and it's still not as important in C as in C++, because in C++ types sometimes have long names. This support was not deemed important when C was created, and it's still not as important in C as in C++, because in C++ types sometimes have long names.

Here, before assigning the variable, we specify the type of data it would store.在这里,在分配变量之前,我们指定它将存储的数据类型。

No, that's a mischaracterization.不,这是一个错误的描述。 You present a declaration of variable age that happens to include an initialization.您提供了一个变量age声明,该声明恰好包含一个初始化。 Initialization is not assignment.初始化不是赋值。 Although in many cases you could separate that into a declaration without initialization and a separate assignment, there are cases where that would not be valid.尽管在许多情况下,您可以将其分离为没有初始化的声明和单独的赋值,但在某些情况下这是无效的。 Overall, the declaration is the primary element in the code presented, not the initialization.总的来说,声明是代码中的主要元素,而不是初始化。

Does we define it just to tell the compiler/interpreter how many bytes the value will occupy in memory.我们是否定义它只是为了告诉编译器/解释器该值将在 memory 中占用多少字节。 No other reason?没有其他原因?

We specify the data type because modern C requires variables to be declared before use, and the data type is a required part of the C syntax for variable declarations.我们指定数据类型是因为现代 C 要求在使用前声明变量,并且数据类型是 C 语法中用于变量声明的必需部分。 At the language level, that's why, end of story.在语言层面,这就是为什么,故事的结尾。

As for what benefits that yields, yes, it does convey how much storage to reserve.至于产生什么好处,是的,它确实传达了要保留多少存储空间。 More importantly, however, it relieves the language implementation from any need to store, track, or dynamically determine objects' types at runtime.然而,更重要的是,它使语言实现不再需要在运行时存储、跟踪或动态确定对象的类型。 The resulting bare-bytes object representations are, generally speaking, congruent with the underlying machine data model.得到的裸字节 object 表示通常与底层机器数据 model 一致。 This is memory efficient (which was an order of magnitude more important when C was designed than it is now), and CPU efficient.这是 memory 高效(在设计 C 时比现在更重要一个数量级),并且 CPU 高效。

C code is also amenable to type-based static analysis, which helps detect (some) bugs early, and it supports a wider variety of basic data types than dynamically typed languages such as Python do. C 代码也适用于基于类型的 static 分析,这有助于及早发现(一些)错误,并且它支持比动态类型语言(例如 ZA7F5F35426B627411FC923B)更广泛的基本数据类型。

And speaking of Python, do note that even this poster child for dynamically-typed languages now supports data type annotations to provide a few of the advantages that static typing has to offer.说到 Python,请注意,即使是这个动态类型语言的典型代表现在也支持数据类型注释,以提供 static 类型必须提供的一些优势。

Consider this function:考虑这个 function:

int add(int a, int b)
{
    return a+b;
}

This function can be typically compiled as an instruction to add two registers and an instruction to return (plus possibly some other instructions needed to implement proper routine interfaces on the platform).此 function 通常可以编译为添加两个寄存器和返回指令的指令(可能还包括在平台上实现适当的例程接口所需的一些其他指令)。

If we did not know what types the arguments were, the compiler would have to generate code to add any possible types of arguments: One-byte integers, two-byte integers, four-byte integers, wider integers, floating-point numbers, strings (for which “adding” them might concatenate the strings), and other support types.如果我们不知道 arguments 是什么类型,编译器必须生成代码来添加 arguments 的任何可能类型:一字节整数、二字节整数、四字节整数、更宽整数、浮点数、字符串(为此“添加”它们可能会连接字符串)和其他支持类型。 Further, it would have to generate code to handle different types of arguments: One might be an integer while the other is a string.此外,它必须生成代码来处理不同类型的 arguments:一个可能是 integer 而另一个是字符串。

Specifying the types of the arguments makes it possible to generate programs that are tailored to specific tasks with specific data types, and this yields programs that are much smaller and faster.指定 arguments 的类型可以生成针对具有特定数据类型的特定任务的程序,从而生成更小更快的程序。

A variable's type determines the values that the variable can have and the operations that can be performed on it.变量的类型决定了变量可以具有的值以及可以对其执行的操作。

Programming languages like C, C++, and Java are statically-typed programming languages. C、C++ 和 Java 等编程语言是静态类型的编程语言。 The word "static" here means we need to determine the types at compile time.这里的“静态”一词意味着我们需要在编译时确定类型。 One way to do that is to just specify the type directly in the code.一种方法是直接在代码中指定类型。 It makes it easier to implement compilers and for developers to read the code.它使编译器的实现和开发人员阅读代码变得更加容易。 Another way I know is type inference.我知道的另一种方法是类型推断。 So instead of specifying the types in the code, we let the compiler infers the types based on the context.因此,我们不是在代码中指定类型,而是让编译器根据上下文推断类型。 The any type in C++ does exactly that. C++ 中的any类型正是这样做的。

Different from statically typed languages, dynamically typed languages like Python and Javascript determine the types at runtime.与静态类型语言不同,动态类型语言如 Python 和 Javascript 在运行时确定类型。 The benefit is that the code is usually more concise and you can do crazy things like conditionally returning different types of data in a function.好处是代码通常更简洁,你可以做一些疯狂的事情,比如在 function 中有条件地返回不同类型的数据。 The downside is that it makes code maintenance significantly harder and easier to produce bugs.缺点是它使代码维护变得更加困难并且更容易产生错误。 That's why we now have Typescript and type annotations in Python to mitigate these problems.这就是为什么我们现在有 Typescript 和 Python 中的类型注释来缓解这些问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我们需要在从 C 中的 function 分配返回值之前声明变量数据类型? - Why we need to declare variable data type before assigning a return value from a function in C? 为什么C中的printf需要指定数据类型 - why do printf in C need to specify type of data 为什么我们在将变量传递给 scanf 时需要地址运算符(与号,&),但在分配给它时不需要? - Why do we need the address-of operator (ampersand, &) when passing a variable to scanf, but not when assigning to it? 为什么我们需要在C ++ printf函数中指定格式说明符中的类型? - Why do we need to specify type in format specifiers in the C++ printf function? 为什么我们在 xchg() 之前需要 pushcli()? - Why do we need pushcli() before xchg()? 我们什么时候需要提及/指定数字文字的整数类型? - When do we need to mention/specify the type of integer for number literals? 嵌套在 C 中的结构中时,为什么我们需要声明联合类型的变量? - Why do we need to declare a variable of union type when nested in a structure in C? 为什么在C中使用函数之前需要声明它们? - Why do we need to declare functions before using them in C? 为什么我们需要在链表的function的名字前加一个*? - Why do we need to add a * before the name of a function for linked list? 为什么我们需要在 execvp 之前在管道上调用 close? - Why do we need to call close on pipes before execvp?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM