• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ints and arrays........

 
sonir shah
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What will be the result of attempting to compile and run the following class?

Options:
1)The code will print i=1 iArr[0]=1;
2)The code will print i=1 iArr[0]=2;
3)The code will print i=2 iArr[0]=1
4)The code will print i=2 iArr[0]=2
5)The code will not compile
Answer :
2)The code will print i=1 iArr[0]=2
In this case, iArr[0] =2 (Agreed), but why is the value of i still 1, rather it should be incremented to 2??
Sonir
 
Rajinder Yadav
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
because i is passed by value not by reference
 
Younes Essouabni
Ranch Hand
Posts: 479
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i is passed by value and your array is passed by reference.
So once you get out of the incr method(), value of i is 1.
 
Younes Essouabni
Ranch Hand
Posts: 479
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What if you do this???


 
Rajinder Yadav
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Essouabni, the variable i is not defined in the scope of method void incr(int n), it is local to main()
You will get a compile error in your case.
Originally posted by Essouabni Younes:

<hr></blockquote>[/QB]
 
Younes Essouabni
Ranch Hand
Posts: 479
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Right, I just wanted to see if you were aware of it.
Sorry, I didn't pay attention
[ January 25, 2002: Message edited by: Essouabni Younes ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic