• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

++ operator (C & Java)

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
consider the folowing code:
int i = 0;
i = i++;
System.out.println(i);
when run, it outputs 0 to the console while the same code in C/C++ outputs 1
Shouldn�t this output be the same since I�m first atributing i�s current value to i and then incrementing i by one ??
Is it just me, am I missing something or is this weird?
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It should be 1 in both languages, as simple as that.
In the second line of your code, i is assigned a value of ( i+1 ).
By the time the third line executes, i is 1, no matter if you use a prefix or postfix ++ operator.
Maybe there's a typo in your code?
What causes confusion to most programmers is the difference between:
System.out.println ( i++ );
and
System.out.println ( ++i );
where the first outputs 0, and the second outputs 1 (if i = 0 at start).
This is because a postfix ++ operator first uses the value of i in the command (System.out.println), and then adds 1 to i.
In the second case, the prefix operator first adds 1 and then uses the value of i (incremented by then).
Hope this can clarify things.
Regards,
G�nther.
http://www.javacoding.net
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually the correct result is 0.
This has been asked (and answered) countless times in programmer certification. Try to do a search here for the previous threads on it. You find a ton.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oops ... my answer was a bit fast.
I overlooked one thing:
the line "i = i++;"
doesn't modify i, since "i++" evaluates to i, then i is incremented, and then the value of the evalutation (i++) is put into i.
This makes that in the end, i is 0 again.
G�nther.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
This link is to a past discussion on this very topic.
Good Luck,
-Dirk Schreckmann
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And...
This conversation is also taking place today over in the Programmer Certification Study thread, which leads to this explanation from earlier this month.
Good Luck,
-Dirk Schreckmann
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic