-
Post Increment Operator
When the piece of code given below when executed in java and c++
gives different results in java and c++.
class Test
{
public static void main(String args[])
{
int a=2;
System.out.println("a " + a);
a=a++;
System.out.println("a " + a);
a=++a;
System.out.println("a " + a);
}
}
the Output when run in java is :
a2
a2
a3.
in c++ it is :
a2
a3
a4
----------------
Was this implementation intentional in java.If so whats the reason.
Mathi Ezhil
(India)
-
Re: Post Increment Operator
I don't know. But why are you doing that? Just do
int a=2;
System.out.println("a " + a);
a++;
System.out.println("a " + a);
++a;
System.out.println("a " + a);
-
Re: Post Increment Operator
I would say that, in this particular case, java's interpretation of that code
makes more sense, and it doesn't matter anyway because the code is self-defeating.
In particular, "a=a++" means, increment 'a' but return the value before it
was incremented, assign that before-incremented value to 'a'. So the assignment
cancels the increment.
Perhaps the operator precidence rules are different between the two languages,
but it is a non-issue to me because the code is not just unrealistic; it
invites trouble.
Did you think that "a=a++" means the same thing as "a=a+1"? You probably
didn't, but if so, read some more about ++ and --.
"mathiezhil" <mathiezhil@rediffmail.com> wrote:
>
> When the piece of code given below when executed in java and c++
>gives different results in java and c++.
>
>class Test
>{
> public static void main(String args[])
> {
> int a=2;
> System.out.println("a " + a);
> a=a++;
> System.out.println("a " + a);
> a=++a;
> System.out.println("a " + a);
> }
>}
>
>the Output when run in java is :
>a2
>a2
>a3.
>
>in c++ it is :
>a2
>a3
>a4
>----------------
>Was this implementation intentional in java.If so whats the reason.
>
>
>Mathi Ezhil
>(India)
-
Re: Post Increment Operator
It is very simple: C is right and Java is wrong.
a=++a; means:
1. a = a;
2. a = a + 1;
a=++a; means:
1. a = a + 1;
2. a = a;
The two statements in question are 2 sequential low level ops packed in a
single high level statement.
F.
-
Re: Post Increment Operator
"Fotios" <fotios@altavista.net> wrote:
>
>It is very simple: C is right and Java is wrong.
>
>a=++a; means:
Sorry I meant a=a++; here
>
>1. a = a;
>2. a = a + 1;
>
>
>
>a=++a; means:
>
>1. a = a + 1;
>2. a = a;
>
>
>The two statements in question are 2 sequential low level ops packed in
a
>single high level statement.
>
>F.
>
>
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks