问题
I'm reading Gilles Dowek's Principles of Programming Languanges:
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.
So, why is this declaration of variables valid? When am I going to use it?
回答1:
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.
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.
回答2:
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.
回答3:
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.
- 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)
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).
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.
回答4:
If Java were to require that fields of a class object must always be written before they were read, this would require that either
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.
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.
回答5:
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'.
回答6:
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.
If my initial deceleration is set to 0 or "" 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.
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 0 or true your 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 NaN by the time you utilize x than your data collection and validations are likely the source of the problem.
In general declare all values at the top and avoid setting generic values unless you have to. If you are going to define the values of x later than don't set it to int x = 0;.
回答7:
Something like:
//declare without giving value.
int i;
//set value
i=9;
来源:https://stackoverflow.com/questions/13788067/why-is-it-possible-to-declare-a-variable-without-an-initial-value