开发者

continue statement inside for loop and if condition [closed]

开发者 https://www.devze.com 2023-04-13 02:39 出处:网络
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.

Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.

Closed 9 years ago.

Improve this question

I have following code snippet and the output i am getting is 4. Please explain me if it takes i=2 or 0. I am confused. And How output was 4?

开发者_StackOverflow社区int main() {  
   int i=2;
   for(i=0;i<2;i++) {
      i=i%3;
      if(i==2) {
          i++;
          continue; }
      else
          ++i;  
   }
   printf("%d",i); 
}


The loop starts with i = 0. Both the if and the else to exactly the same thing. Increment i and continue.
If you use a bit of logic, the whole block can be reduced to i++ (i = i % 3 has no effect since i < 2).

It's not possible to get 4 with the code you posted.


The output cannot be 4 for the program you posted, because by the time the loop breaks, the value of i would be 2, not 4 and the loop will run exactly once.

Also, your code never enters the if block, because the condition is i==2 which can never be true inside the for loop, as by that time the loop would be exited.

So your code is equivalent to this:

int main() {  
   int i=2;
   for(i=0;i<2;i++) {
      i++;
   }
   printf("%d",i); 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号