Click to See Complete Forum and Search --> : problem with post increment operator


vshuk
October 9th, 2000, 01:10 AM
JVM BUG???

Consider the following code

public class Test
{
public static void main(String arr[])
{
int i=0;
i=i++;
System.out.println|("Value of i is "+i);
}

}

What is the o/p??
I thought it should be 1..but it prints 0..ie the i++ part is ignored..
Can someone explain why??

Phill
October 9th, 2000, 04:34 AM
Hi there
This is not a bug.
Done this way :
int i = 0;
int a = i++;
a is given the value of i before i is incremented,
To get the incremented value simply place the ++
before the i instead of after ie:
int i = 0;
int a = ++i;

Phill.

vshuk
October 9th, 2000, 04:47 AM
Hi Phill,
You are right. We can another variable for evaluating the incremented values but can you explain how value is assigned to i in following statement-
i = i++;
Expecting a briefing .
Thanks.

Phill
October 9th, 2000, 05:26 AM
Hi
Yes that is weird , it seems that i isnt incremented at all.
I have taken a quick look at the bug list
and i didnt see it there, although i only
browsed three pages.
I have never noticed this before as i have never
coded that way, i always use this way:

i = i + 1;

Maybe you can submit this to Sun and see if it
is a bug.
Phill.

Phill
October 9th, 2000, 05:26 AM
Hi
Yes that is weird , it seems that i isnt incremented at all.
I have taken a quick look at the bug list
and i didnt see it there, although i only
browsed three pages.
I have never noticed this before as i have never
coded that way, i always use this way:

i = i + 1;

Maybe you can submit this to Sun and see if it
is a known bug.
Phill.

vshuk
October 9th, 2000, 05:53 AM
Hi Phill,
Well I think the controls flows the following way for the statement
i = i++;
First the right expression is evaluated . Lets say value is stored internally in a temporary variable temp1. After this evaluation value of 'i' is incremented by 1. Then the assignment to variable 'i' takes place . So 'i' gets value of temp1 which is zero (So the value i=1 is overwritten).
Thanks for ur views.

weaver
October 9th, 2000, 08:58 AM
Actually no it isn't strange. At the time the line i = i++ is executed, i is equal to 0. Then you tell it to let i equal i, and then increment i. However you are only incrementing the 'copy' of i that is on the right side of the equation. If you want to increment a variable by 1, the easiest way is to do the following:

i++;


-------------------------------------------
weaver
icq# 64665116
Please rate this post.
http://weaver.x7.htmlplanet.com