为什么在某些语言中而不是其他语言中使用变量之前,需要先声明该变量? [英] Why do we need to declare the variable before we use it in some languages, but not in others?

查看:45
本文介绍了为什么在某些语言中而不是其他语言中使用变量之前,需要先声明该变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python与Java中如何为变量声明分配内存?没有编译步骤,解释型语言如何知道变量需要多少内存?

How is memory allocated for a variable declaration in Python vs. Java? Without a compilation step how does an interpreted language know how much memory is needed for a variable?

推荐答案

在使用变量之前,必须先为变量分配一个内存位置,然后进行初始化-无论是在 Python ,甚至是徽标.

Before being usable, variables must be allocated a memory location and then initialized--whether in Java, Python, or even Logo.

Declare意味着 you 使该变量以特定的代码片段栩栩如生,(例如以Java为例)

Declare means that you make that variable come to life with a specific snippet of code, with (using Java as an example) something like

int i;
Person p;

这些已声明,但未初始化.现在为它们分配了内存中的位置-在某些语言中,位置和大小可能会不断变化.但是无论如何,运行时环境现在可以查询内存中的某些物理位置,以检索变量(指向它的间接指针或实际位置本身).

These are declared, but not initialized. They are now assigned a location in memory--which, in some languages, may be ever-changing, both in location and size. But regardless, there is now some physical location in memory that the runtime environment can query, to retrieve the variable (either an indirect pointer to it, or the actual location itself).

现在它有一个空的盒子"可以放入其中,必须将其填充,也就是说必须对其进行初始化":

Now that it has an empty "box" in which to go, it must be filled, which is to say it must be "initialized":

i = 3;
p = new Person();

现在盒子里有一些具体的东西.准备使用.尝试在初始化之前使用它(在Java中)会导致 NullPointerException .

Now there is something concrete in the box. It is ready for use. Attempting to use it before its initialized will result (in Java) in a NullPointerException.

某些语言要求您声明变量,以便为其显式分配内存(位置和/或大小).某些语言为您执行此内存分配.如对您的问题和此答案的评论中所述,存在很多差异.

Some languages require you to declare variables, in order to explicitly allocate memory for it (location and/or size). Some languages do this memory-allocation for you. As stated in the comments to both your question and this answer, there's a lot of variation.

这篇关于为什么在某些语言中而不是其他语言中使用变量之前,需要先声明该变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆