• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question on local variables

 
Nikhil Bansal
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

This from Kathy Sierra Chp 2

" The key is to remember that a local variable must be initialized before you try to use it. The compiler will reject any code that tries to use a local variable that hasn�t been assigned a value "


What exactly does it mean

" before you try to use it."

For ex won't the compiler complain in the foll. code.

int i, j;
int k = 0;
j = 2;
k = j = i = 1;


Please post your inputs.

Regards

Nikhil Bansal
 
Joe Harry
Ranch Hand
Posts: 10124
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Nikhil,

Your quote,

For ex won't the compiler complain in the foll. code.

int i, j;
int k = 0;
j = 2;
k = j = i = 1;


It means that you cannot use the uninitialized variable on the right hand side of the = operator. Now in the above code, the compiler interprets it as

k = j = i = 1 as k = (j = (i = 1)) and it works. As you can see that the variable i is not at the righthand side of the operator and by the time it comes to the right had side of the = operator, it already has the value set to 1.

Hope you got it.

Regards,
Jothi Shankar Kumar. S
[ November 01, 2006: Message edited by: Jothi Shankar Kumar Sankararaj ]
 
Henry Wong
author
Marshal
Pie
Posts: 21184
80
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What exactly does it mean

" before you try to use it."

For ex won't the compiler complain in the foll. code.

int i, j;
int k = 0;
j = 2;
k = j = i = 1;


Try...

int i, j;
int k = i + j;

For local variables, this shouldn't compile...

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic