-4

Why is the code below resulting in an infinite loop?

#include <stdio.h>
void main()
{
  int i;
  for(i=0;i!=12;i++)
  {
    printf("%d\n",i);
    i=12;
  }
}
Jonathan Leffler
  • 666,971
  • 126
  • 813
  • 1,185
Tarun Dev
  • 21
  • 1
  • 3
    `i++` is excecuted at the end of the loop so i will become `i=13` – Jérôme Apr 24 '17 at 15:21
  • ask yourself whether (12+1) == 12 is ever true. – WhozCraig Apr 24 '17 at 15:21
  • because after loop operation `i++` is executed so you set `i=12` than you increment it with `i++` and then new iteration is performed which checks if `i!=12`.. I recommend you, if you don't exactly know what the program is doing, use debugger to found out what it is doing. – Gondil Apr 24 '17 at 15:22
  • See [What should `main()` return in C and C++](http://stackoverflow.com/questions/204476/). – Jonathan Leffler Apr 24 '17 at 20:04

3 Answers3

2

Because i never equals 12 when it's checked by the loop. You execute i++ after each loop iteration, so i always equals 13 when it's checked.

You can omit the i++ part entirely, or set i = 11; instead to accomplish the same thing. (Of course, since "the same thing" in this case is only ever wanting a single iteration of the loop, you don't really need a loop in the first place. But I assume this is just a contrived learning exercise.)

David
  • 176,566
  • 33
  • 178
  • 245
1

i++ is excecuted at the end of the loop so i will become 13

Jérôme
  • 1,133
  • 2
  • 16
  • 21
1

It happens because the for loop increments the variable before checking the loop condition.

Here's the code with the for loop rewritten as a while loop:

#include<stdio.h>
 void main()
{
  int i;
  i=0;
  while(i!=12)
  {
     printf("%d\n",i);
     i=12;
     i++;
  }
}

And here's its output (the first few lines):

0
13
13
13
...

Each time through the loop, the code sets i to 12, and then immediately increments it to 13 before checking the condition and restarting the loop. The loop will only terminate when i==12, so it will run forever.

mwfearnley
  • 2,377
  • 1
  • 27
  • 29