Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Looping doubt

 
abin joy
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
code
----------------------
case 0:
{

for (int x=10;x>5;x++)

if(x>10000000)

x=10;

break;

}
---------------------------
code

In the above given code why we have omitted the braces for the for loop even though a block of statements were there.How will the execution flow happen in this case?
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
please tell me what you get,the time of execution ?
 
Henry Wong
author
Marshal
Pie
Posts: 20894
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the above given code why we have omitted the braces for the for loop even though a block of statements were there.How will the execution flow happen in this case?


The "braces" are not required for the "for" loop. By default, the loop will execute the next line only. The braces are only necessary if you want to execute more than one line.

Henry
 
Rob Spoor
Sheriff
Pie
Posts: 20495
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by abin joy:

With proper indentation you can see the flow a lot better.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12086
29
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
a "for" statement basically has two parts... the "for (;;) " part, followed by a statement or a block (curly braces).

an "if" statement basically has two parts... the "if (condition)" part, followed by a statement or a block (curly braces).

so, the compiler sees your "for (int x=10;x>5;x++)", and says "ok, put the next statement or block inside the loop.". the next thing it finds is the "if" statment, and so it take the whole thing - both parts - because that single statement has two parts.

[edit]Disable smilies. CR[/edit]
[ September 09, 2008: Message edited by: Campbell Ritchie ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic