try to compile and run this progs... class testpp { public static void main(String[] args) { int i=0; i=i++; System.out.println("Hello World!"+i); } } why o/p is 0 not 1???it is 1 in 'c' and 'c++'....pls tell me soon.
Jo Oehrlein
Greenhorn
Joined: Jan 03, 2001
Posts: 11
posted
0
This was discussed in http://www.javaranch.com/ubb/Forum24/HTML/008856.html also. The output of the program is 1 if you change the i=i++ to just i++. Essentially, the post increment is lost. jo [This message has been edited by Jo Oehrlein (edited March 29, 2001).] [This message has been edited by Jo Oehrlein (edited March 29, 2001).] [This message has been edited by Jo Oehrlein (edited March 29, 2001).]
Sameer Sachdeva
Greenhorn
Joined: Mar 29, 2001
Posts: 5
posted
0
thanx jo but can u explain me why post increment is lost in java.it is not lost in 'c' and 'c++'. anyway thanx best regards Sameer
Jo Oehrlein
Greenhorn
Joined: Jan 03, 2001
Posts: 11
posted
0
I've updated my first response with the correct URL. Sorry about that. In that thread, James Baud had a good explanation for why the post increment is thrown away. Yes, this is different than c and c++.
Lafayette Hubert
Greenhorn
Joined: Mar 01, 2001
Posts: 5
posted
0
Technically, in C/C++ that operation's behavior is undefined. Different compilers will likely do different things. Things like that are pretty contrived and rarely if ever necessary.
Originally posted by Sameer Sachdeva: try to compile and run this progs... class testpp { public static void main(String[] args) { int i=0; i=i++; System.out.println("Hello World!"+i); } } why o/p is 0 not 1???it is 1 in 'c' and 'c++'....pls tell me soon.
No offense meant but... I've seen a number of threads here on this same topic. I can appreciate that some folks might have an academic need to understand exactly what happens in such a statement. For all practical purposes though, I don't see why you would even dwell on code like that. If I see code like that at work, I would not spend 2 seconds trying to second guess the compiler. I would just find out what really needs to happen then replace that line with clearer code. And don't worry that you'll encounter that type of question in the certification exam because you most probably won't. My $0.02 J.Lacar, SCJP2
[This message has been edited by JUNILU LACAR (edited March 29, 2001).]
why o/p is 0 not 1???it is 1 in 'c' and 'c++'....pls tell me soon.
You should note that this operation is undefined in C/C++. It works one way on some machines and another way on other machines. That is the HUGE adavantage that Java has over C/C++. You may not like the behavior but it is clearly defined and consistent. ------------------ Moderator of the JDBC Forum