Variable assignments and initialization Flashcards

1
Q

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

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

For LOCAL variables (not instance variables),

When can variables be chained?

A
  • 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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly