Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

for loop with preincrement?

 
adam faith
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
In the following code
for(int j = 0 ; j < 2; ++j)
{
System.out.println("j =" +j);
}
I thought the output would be
j = 1
But the output is
j = 0
j = 1
Am i missing something here, i thought the preincrement was done before the the output statement was executed?
Can sombody help, thanks
 
Neil Laurance
Ranch Hand
Posts: 183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Think of it like this:
for( <init>; <test>; <next> ) {
<block>;
}
Is analogous to:
<init>;
while(<test>) {
<block>;
<next>;
}
So post or pre increment makes no difference...
Cheers, Neil
[ September 14, 2002: Message edited by: Neil Laurance ]
 
adam faith
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Niel
 
Frank Carver
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As an aside, I tend to prefer "preincrement" for everything unless the (slightly peculiar) postincrement semantios are a vital part of the solution. I find that it's easier to say ("increment i"), easier to understand (it's exactly the same as "i += 1", and looks more like a method call.
I write all my "for" loops using preincrement, and whenever I have a stand-alone increment in a method, I use preincrement too.
Others have different opinions, but I think everyone should decide for themselves rather than just using "i++" because that's the way Kernighan and Richie did it in the first edition of "The C Programming Language".
Think about it. Were you ever confused by an inadvertent use of "i++" ?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic