• Post Reply Bookmark Topic Watch Topic
  • New Topic

semicolon after for loop result not as expected  RSS feed

 
Ranch Hand
Posts: 291
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
was writing some simple for loops like this

for (x = 1; x <= 20; x = x+1)

but by accident i did this

for (x = 1; x <= 20; x = x+1);      (Semi colon after the loop)

the first one print 1 to 20 as expected

the second one prints 21

why is this? and why did the ; at the end produce this result?
 
Bartender
Posts: 572
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With the ending semicolon, there is no loop body; any statement after the semicolon is OUTSIDE the loop.
With no semicolon, the next statement is INSIDE the loop body.
 
Rancher
Posts: 2240
28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
second one prints 21

For that to print required that x be defined outside of the for statement.  If you got an error message error: cannot find symbol, that message told you that the print statement was not inside of the for loop.  Moving the definition of x out of the for statement fixed that compiler error but had the code do something you didn't expect.

 
Fred Kleinschmidt
Bartender
Posts: 572
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To be more precise, with a semicolon there, there is only an empty statement in the loop body. It is the same as
which is the same as


Without that semicolon,
is the same as
 
Norm Radder
Rancher
Posts: 2240
28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You rarely want to define a for loop control variable outside of the for statement.
 
jon ninpoja
Ranch Hand
Posts: 291
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes realised what i had done very quickly

thanks guys...this place is great!!!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!