Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

fyi: pre/post increment with exception thrown on the line

 
Jon Dornback
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i just ran in to a situation where i am converting a string to a number and then inserting the number in to an array. i thought this code sample might be helpful for newbies - i sure learned something.

anything pre/post increment/decrement on the line before the exception is thrown is on the stack and will be executed (k++,++n1), but anything after the exception is not (++n2). also try n1++, etc, just for fun. hope this helps someone avoid logic errors :-)
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Of course, simply not trying to do too many things at once and on a single line would greatly improve the readability of the code as well as reduce the likelihood of any logic errors.
So, rather than trying to do something like,
array[ i++ ] = ++j ;
just break it apart and say what you mean, one thing at a time
++j ;
array[ i ] = j ;
++i ;
 
Sayed Ibrahim Hashimi
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

array[ i++ ] = ++j ;
just break it apart and say what you mean, one thing at a time
++j ;
array[ i ] = j ;
++i ;

If I'm not mistaken the bytecode(if not then the assembly) generated for both of these is going to be the same, so it doesn't improve performance to do it the "short" way.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic