How does scope interact with variable declaration, initialisation, and assignment? The definition of those terms based on what I have learned so far is listed below:
Declaration: States the type of a variable, and it's name/identifier. Variables must have been declared before they can be assigned or read.
Assignment: Throws away the existing value of a variable and replaces it with a new one, the old value is thrown away at the end of the assignment statement, so the value can be incremented or otherwise adjusted, for example: x = x + y;
Initialisation: The name used for the first assignment of a variable, before initialisation, a variable has a default value, in the case of objects, those objects have a null value. Initialisation can be done in conjunction with declaration.
Scope: The "lifespan" of a variable, a variable is in scope until the end of the code block, at which point the memory used to store that variable is freed up. In effect, the variable is deleted or "killed", when the code block ends.
What I don't know is how scope interacts with Declaration and assignment. While the scope of a variable seems to be based solely on the code block in which it is Declared, I don't know how assignment interacts with scope. For example:
public class exampleClass
{
public static void main(String[] args) // using java for example
{
int x = 5; // x is declared here, and initialised with a value of 5
for (int i = 0; i < 10; i++) // i is declared and initialised here
{
x = i; // x is assigned the value of i each iteration
} // i goes out of scope here
System.out.println(x); // the value of x is printed
} // x goes out of scope here
}
In this example, x is declared and initialised (do we just say initialised?) in the main method, and is in scope for that method. However, x is assigned a value in the while loop. What will be printed when this code is executed, but more importantly why? Will it print "5", or "9"?
I have seen code throw up compiler exceptions because of syntax that would imply that x should print 5. However when I run this example code, I get "9".
One final question, why is it that multiple variables can be declared and initialised inline:
int x = 1, y = 4, z = 6;
But variables cannot be assigned inline:
x = 1, y = 4, z = 6;