1

If I have the following code, what will the integer "i" be equal to after it executes? Does a loop increment after a break statement?

int i = 0;
for(int foo = 0; foo < 10; foo++,i++){
    break;
}
8
  • 8
    Have you tried it? ideone.com Commented Nov 17, 2011 at 0:21
  • 1
    Why don't you execute it and print out i? Commented Nov 17, 2011 at 0:22
  • 3
    The break executes before the update part, so i doesn't change. Commented Nov 17, 2011 at 0:24
  • 2
    Homework question? Looks like it. Commented Nov 17, 2011 at 0:25
  • 2
    I feel it is morally incorrect to answer this question . No such thing as a stupid question but surely a there is a thing called Lazy question. Commented Nov 17, 2011 at 0:41

4 Answers 4

5

After a for loop finishes one iteration it executes the incrementor code (in your case foo++,i++). Since your loop breaks before it finishes one iteration neither foo nor i increments.

Sign up to request clarification or add additional context in comments.

Comments

4

You can actually look this up in the standard. A for loop with a break, by definition, is like a while, goto, as so:

for( init; test; incr){
   break;
}

is

init
while(test){
   // do things
   goto end
   incr
}
end:

So, since the break is always executed, it never hts the increment part, and neither foo nor i will be incremented.

Comments

3

Why don't you put a println and see...

I'm going to say it ends up with what you started (i.e., zero -- the increment happens after the code in inside the for executes -- since you break out of it, it never gets to increment).

4 Comments

Your answer should be a comment.
Every time i ask a question here i re read it later and feel like an idiot. :P
Why do people keep upvoting Hunter? Originally I just had my snippy comment but I have actually answered it now.
Because it's obviously homework and 'answers' are discouraged. See stackoverflow.com/tags/homework/info
0

It prints 0, which is exactly what you should expect it to print. The post increment clause is executed after the code block, but we are breaking in the middle of the code block. So the post increment is never executed.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.