java 为什么可以声明没有初始值的变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13788067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is it possible to declare a variable without an initial value?
提问by Billy Rubina
I'm reading Gilles Dowek's Principles of Programming Languanges:
我正在阅读 Gilles Dowek 的编程语言原则:
He says that it's also possible to declare a variable without giving it an initial value and also that we must be careful not to use a variable which has been declared without an initial value and that has not been assigned a value. This produces an error.
他说也可以声明一个变量而不给它一个初始值,而且我们必须小心不要使用一个没有初始值声明并且没有赋值的变量。这会产生错误。
Note:The book's author mentions the possibility of declaring variables without an initial value on Java.
注意:本书的作者提到了在 Java 上声明没有初始值的变量的可能性。
So, why is this declaration of variables valid? When am I going to use it?
那么,为什么这个变量声明是有效的呢?我什么时候要用它?
回答by
There are many different reasons for many different languages.
许多不同的语言有许多不同的原因。
MEMORY
When you declare a variable, you want some memory to hold the variable in. This involves asking the kernel of the operating system for memory, or some kind of monitoring program which keeps track of memory. In short, this can be an expensive operation.Hence, in many cases, it is desirable to allocate all the memory required for the object at the same time, and then assign whatever value has to be assigned to it later. This way, you can increase the performance of the program in the critical parts. This use case is common enough that a feature allowing declaration without initialization is allowed. However, good practices assert that in all other cases you should initialize the variable while assigning.
内存
当你声明一个变量时,你需要一些内存来保存变量。这涉及向操作系统内核询问内存,或者某种跟踪内存的监控程序。简而言之,这可能是一项代价高昂的操作。因此,在许多情况下,希望同时分配对象所需的所有内存,然后分配稍后必须分配给它的任何值。这样,您可以在关键部分提高程序的性能。这个用例很常见,以至于允许在没有初始化的情况下进行声明的功能是允许的。但是,良好的做法断言,在所有其他情况下,您应该在分配时初始化变量。
Think of the memory allocation as a bureaucracy. There is too much paper work. So, if you know you are going to use a large amount of memory later, you ask for a large amount of memory upfront in one single transaction, rather than asking the kernel each next time.
将内存分配视为官僚主义。文书工作太多了。因此,如果您知道稍后将使用大量内存,那么您可以在单个事务中预先请求大量内存,而不是每次都询问内核。
EXPENSIVE INITIALIZATION
This point is very similar to the above point. Suppose you have a 1 million times 1 million array. Initializing such an array is an expensive procedure. To do so with defaults would be stupidity, and hence, such a feature, where memory is allocated and then used as needed.
EXPENSIVE INITIALIZATION
这一点与上一点非常相似。假设您有一个 100 万乘以 100 万的数组。初始化这样的数组是一个昂贵的过程。使用默认值这样做是愚蠢的,因此,这样一个功能,内存被分配,然后根据需要使用。
In here, its like you are buying a huge amount of lego blocks to construct something, but you want to buy them in shapes of the default spiderman. The shopkeeper or you would have to extra hard to get them in shapes of spiderman when you are anyway going to reshape them later.
在这里,就像您要购买大量乐高积木来构建某些东西,但您想购买默认蜘蛛侠形状的它们。店主或您将不得不更加努力地将它们变成蜘蛛侠的形状,当您以后无论如何要重塑它们时。
回答by alestanis
For example, you could have something like this:
例如,你可以有这样的事情:
int i;
if (first_condition)
i = 1;
elseif (second_condition)
i = 2;
else
i = 0;
Your variable would need to be declared outside the if
for it to be used later, but its value is fixed inside the if
conditions.
您的变量需要在 外部声明if
以便稍后使用,但其值在if
条件内是固定的。
回答by BuddhiP
If you really look at what happens when you declare a variable and initialize it (assign an initial value), you will see that down at machine instruction level, or byte code for Java there is a significant amount of computational power being used in both these steps.
如果你真的看看当你声明一个变量并初始化它(分配一个初始值)时会发生什么,你会发现在机器指令级别,或者 Java 的字节码,在这两个方面都使用了大量的计算能力脚步。
- declaring the variable means allocating memory, creating an instance of asked type, etc etc
- Then initializing that location of memory, again requires more processing to move the default value to the allocated memory location, like filling it with 0s if the default value is 0. (Note: when random memory location is allocated to a variable that memory could contain any pattern, left there by a previous value)
- 声明变量意味着分配内存、创建请求类型的实例等
- 然后初始化该内存位置,再次需要更多的处理来将默认值移动到分配的内存位置,例如如果默认值为 0,则用 0 填充它。(注意:当随机内存位置分配给内存可能包含的变量时任何模式,由以前的值留在那里)
So if user unknowingly use a variable without first giving it an acceptable value for its type, then there could be an error if the value which was there was not correct.
因此,如果用户在不知情的情况下使用变量而没有先为其类型提供可接受的值,那么如果存在的值不正确,则可能会出现错误。
So if a language forces you to initialize a variable (or does so by itself) at declaration then it reduces chances for an error down the line, but it may be wasting processing power for something you didn't really want.
因此,如果一种语言强制您在声明时初始化一个变量(或自行初始化),那么它会减少出现错误的机会,但它可能会浪费处理能力来处理您并不真正想要的东西。
On the other hand, if it allows you to declare a variable without initializing it, it gives you the control and may be saving some computing power for you but open the chances for an error. (Assume you have a scenario where your initial value for the varible depends on some other conditions, which are going to consider and assign the variable accordingly. In such case initializing the var at declaration could be just waste processing power).
另一方面,如果它允许您在不初始化的情况下声明一个变量,它会给您控制权,并且可能为您节省一些计算能力,但也增加了出错的机会。(假设您有一个场景,其中变量的初始值取决于其他一些条件,这些条件将考虑并相应地分配变量。在这种情况下,在声明时初始化 var 可能只是浪费处理能力)。
Languages decide which path they want to take, mostly depend on what they consider their power is.
语言决定他们想走哪条路,主要取决于他们认为自己的力量是什么。
if it is about giving the programmer a chance to have control, and make highly optimized programs then they will usually allow declaring vars without initializing, in addition to more stuff.
如果是为了让程序员有机会控制并制作高度优化的程序,那么除了更多内容之外,他们通常会允许在不初始化的情况下声明变量。
But if the language is about forcing to programmer to write more error free programs it would take the other path.
但是,如果语言是要强迫程序员编写更多无错误的程序,那么它就会走另一条路。
回答by supercat
If Java were to require that fields of a class object must always be written before they were read, this would require that either
如果 Java 要求类对象的字段必须始终在读取之前写入,这将要求要么
The constructor of a class object must write to all fields of that object, including ones which would code would never read without having written them a second time later on; this would be both ugly and inefficient.
Every field must be able to hold a
never been written
value which is different from any other value that can be written to it.The compiler would have to solve the Halting Problem to determine whether a field could be read without having been written.
The language must accept the possibility that a field will be read without user code having written it.
类对象的构造函数必须写入该对象的所有字段,包括那些代码如果没有第二次写入它们就永远不会读取的字段;这既丑陋又低效。
每个字段都必须能够保存一个
never been written
不同于任何其他可以写入它的值的值。编译器必须解决暂停问题,以确定是否可以在未写入的情况下读取字段。
该语言必须接受这样一种可能性,即在没有用户代码编写的情况下读取字段。
Of these possible choices, #4 is the least evil. To avoid undefined behavior, Java defines the behavior of reading a field that has never been written: it will contain a default value for its type.
在这些可能的选择中,#4 是最不邪恶的。为了避免未定义的行为,Java 定义了读取从未被写入的字段的行为:它将包含其类型的默认值。
回答by Bob
Ok here is an example. I am currently setting global values that are set to persistent on a PDF forums. For this application I want to uses these values as data storage much like a text field. Not the best method but it works for this example. Rather than populated my forum with hundreds of hidden text fields I can set the values as a persistent global variables.
好的,这是一个例子。我目前正在设置在 PDF 论坛上设置为持久的全局值。对于这个应用程序,我想像文本字段一样使用这些值作为数据存储。不是最好的方法,但它适用于这个例子。我可以将值设置为持久性全局变量,而不是用数百个隐藏文本字段填充我的论坛。
If my initial deceleration is set to 0or ""as a value of the variable than it will not keep data between sessions. The initialization of the forum will reset the value to nothing. Much like Scrips, forums operated in order. It will recognize all of the scripts in the document first, before assigning values to carry over variables. Thus it is necessary to declare the variable without a value, so that the initialization does not replace the values.
如果我的初始减速设置为0或“”作为变量的值,则它不会在会话之间保留数据。论坛的初始化会将值重置为空。就像 Scrips 一样,论坛按顺序运行。它将首先识别文档中的所有脚本,然后再为结转变量赋值。因此有必要声明没有值的变量,以便初始化不会替换值。
In general it is also good house keeping to declare all of your variables at the top. It is possible to declare them as you go, but I have found that when a new element is added to a Script I have to move lines up and down to keep my code clean. If the variable is declared when it is used, than it also becomes very easy to use a variable before it is declared, which does not work.
一般来说,在顶部声明所有变量也是很好的内务管理。可以随时声明它们,但我发现当向脚本添加新元素时,我必须上下移动行以保持代码整洁。如果在使用时声明变量,那么在声明之前使用变量也变得非常容易,这是行不通的。
Additionally
此外
It is efficient to assign value when declaring, But not generic place holder values. In most scripts int is not as simple as saying int x = 5;More often we call on data such as this.getField("TextBox3").value;or some other line code. By assigning a generic value such as ""or 0or trueyour function may work even if you failed to properly utilize a value. By not assigning a value, if you fail to utilize your variable, than your function will fail allowing you to narrow the possibilities when problem solving. If int x;is still NaNby the time you utilize xthan your data collection and validations are likely the source of the problem.
声明时分配值是有效的,但不是通用占位符值。在大多数脚本中 int 并不像说int x = 5那样简单;更多的时候我们调用诸如this.getField("TextBox3").value 之类的数据;或其他一些行代码。通过分配一个通用值,例如""或0或true,即使您未能正确使用某个值,您的函数也可以工作。通过不分配一个值,如果你不能利用你的变量,那么你的函数就会失败,让你在解决问题时缩小可能性。如果int x; 当您使用x时仍然是NaN比您的数据收集和验证可能是问题的根源。
In generaldeclare all values at the top and avoid setting generic values unless you have to. If you are going to define the values of xlater than don't set it to int x = 0;.
通常,在顶部声明所有值并避免设置通用值,除非您必须这样做。如果您打算稍后定义x的值,请不要将其设置为int x = 0; .
回答by Fanda
I am new to c++, but I think this information may also be helpful.
我是 C++ 的新手,但我认为这些信息也可能会有所帮助。
FROM: Programming: Principles and Practice Using C++:
来自:编程:使用 C++ 的原则和实践:
Why does C++ offer both declarations and definitions? The declaration/definition distinction reflects the fundamental distinction between what we need to use something (an interface) and what we need for that something to do what it is supposed to (an implementation). For a variable, a declaration supplies the type but only the definition supplies the object (the memory). For a function, a declaration again provides the type (argument types plus return type) but only the definition supplies the function body (the executable statements). Note that function bodies are stored in memory as part of the program, so it is fair to say that function and variable definitions consume memory, whereas declarations don't.
为什么 C++ 提供声明和定义?声明/定义的区别反映了我们需要使用什么(接口)和我们需要什么来完成它应该做的事情(实现)之间的根本区别。对于变量,声明提供类型,但只有定义提供对象(内存)。对于函数,声明再次提供类型(参数类型加返回类型),但只有定义提供函数体(可执行语句)。请注意,函数体作为程序的一部分存储在内存中,因此可以说函数和变量定义消耗内存,而声明不消耗内存。
回答by tonyG_cyprus
You can declare an empty var for instance in a validation script,
例如,您可以在验证脚本中声明一个空变量,
$error='';
if(empty($_POST['first_name']{
$error=$error."You did not enter a name";
}
}
like this, but I would only use it if the code immediately after it redeclared it, as above, so that it wouldn't get 'mislaid'.
像这样,但我只会在代码重新声明后立即使用它,如上所述,这样它就不会被“误放”。
回答by user903772
Something like:
就像是:
//declare without giving value.
int i;
//set value
i=9;