Variable assignments and initialization Flashcards
For INSTANCE variables (not local variables),
When can variables be chained?
1- When the left side has a declaration
2- When variables on both sides are already declared
Write examples of each
When the left side has a declaration
The left side must be a (new) declaration (ex: int c)
The right side must have already been declared before.
Example 1.1:
int a,b;
int c =a=b; //ok because left is declaration & right is already declared before.
Example 1.2:
int x = y = z; // does not compile because right side was not declared before.
When variables on both sides are already declared:
This can only be done inside a block.
Example:
int a,b,c;
b=a=c; //will not compile. Left side must be declaration or put it in a block.
b=a=c=9;// will not compile. Left side must be declaration or put it in a block.
int a,b,c;
{a=b=c;} // this works
For LOCAL variables (not instance variables),
When can variables be chained?
- All the variables must be declared first.
- One of the variables can be declared on the left side of the chain statement.
- The rightmost variable must already have a value assigned OR the rightmost must be a value that is getting assigned.
Example 1 - OK
int b;
int c=1;
int a=b=c; // ok because c already has a value.
Example 2 - OK
int a,b,c;
a=b=c=9; // ok because a value is getting assigned.