The Artima Developer Community
Sponsored Link

Java Answers Forum
Post increment problem

3 replies on 1 page. Most recent reply: May 9, 2005 10:14 PM by Bob Dobalina

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 3 replies on 1 page
pradyot sikdar

Posts: 1
Nickname: pradyot
Registered: Mar, 2005

Post increment problem Posted: May 9, 2005 1:54 AM
Reply to this message Reply
Advertisement
Can you please explain the following program.

public class Test
{
public static void main(String []args)
{
int i = 0;
i = i++;
System.out.println(i);
}
}
In java,it will print 0.

But if i write the same logic in C language,it will print 1.
WHY?

----Pradyot


Matthias Neumair

Posts: 660
Nickname: neumi
Registered: Sep, 2003

Re: Post increment problem Posted: May 9, 2005 4:59 AM
Reply to this message Reply
Java offers 2 versions of this operator.

The postfix form changes the value after the assignment is executed, the prefix operator does it before the assignemnt is executed.

Example:
public static void main(String[] args) {
  int m = 7;
  int n = 7;
  int a = 2 * ++m; //a is 16, m = 8
  int b = 2 * m++; //b is 14, m = 8, the increment operator was executed after the "=" operation.
}


It is recommended not to use the ++ operator inside a line with multiple operations.

A common joke about C++: The language should be called ++C, because we want to use it AFTER it was improved.

Matthias Neumair

Posts: 660
Nickname: neumi
Registered: Sep, 2003

Re: Post increment problem Posted: May 9, 2005 5:01 AM
Reply to this message Reply
I made a mistake, this code is the correct one.

public static void main(String[] args) {
  int m = 7;
  int n = 7;
  int a = 2 * ++m; //a is 16, m = 8
  int b = 2 * n++; //b is 14, n = 8, the increment operator was executed after the "=" operation.
}

Bob Dobalina

Posts: 16
Nickname: hiredgoon
Registered: Apr, 2005

Re: Post increment problem Posted: May 9, 2005 10:14 PM
Reply to this message Reply
The behaviour of that line is undefined. If you used a different C compiler i could be 0, or 42, or -1231231. Please don't write code like that.

Flat View: This topic has 3 replies on 1 page
Topic: how can I read a excel file Previous Topic   Next Topic Topic: Applet Not inited, Error

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use