-1

How this for loop is working

int main(){

char i=0;

for(i<=5 && i>=-1; ++i ;i>0)

printf("%d \n",i);

printf("\n");



return 0;

}

5
  • 1
    What do you mean "Working"? Commented Dec 3, 2015 at 2:36
  • 1
    ++i is the same as ++i != 0, and i > 0 is the same as doing nothing, in this context Commented Dec 3, 2015 at 2:38
  • You are experiencing integer overflow which is undefined behavior. You cannot rely on this as it's not guaranteed that it will work. Commented Dec 3, 2015 at 2:40
  • in this context Working is executing . And here i is not declared as an Integer it is declared as a character. Commented Dec 3, 2015 at 2:46
  • @iharob in fact it is implementation-defined behaviour due to out-of-range assignment Commented Dec 3, 2015 at 2:53

4 Answers 4

1

Lets name parts of the for loop:

for( Expr1; Expr2; Expr3 )
   DoStuff;

This is how a for loop works: 1. It executes Expr1 first. in your loop does nothing in fact, since it doesn't check the result of this execution.

  1. Then it executes Expr2 and treat it's result as a condition if it's 0 terminates the loop, if it's "not 0" go to step 3. In your loop this means that i will be incremented, thus it's now 1, so result is true.

  2. Then it runs the DoStuff part, in your case print out i value

  3. Next it executes Expr3, no check, just run it, in your case does nothing again, since it's a condition and its result isn't used.

  4. Next it goes back to Expr2 executes it and check it's result. now i is 2, still a true condition.

  5. Again execute the DoStuff part and go to step 4

The loop will stop once i value changes back to 0. When? since it's type is char, after reaching 127 it will overflow to -128 and then increment back to -1 and then 0. and stop.

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

2 Comments

-128 is not greater than 0 why loop still increment i after overflow ? It should stop at 127
It only checks if i is equal to 0 or not. doesn't matter of i is negative or positive. [ i == 0 -> false ] [ i != 0 -> true ]
1

Ahh thanks for the clarification.

Your asking why the for loop in your example is executing, even though the increment operand and loop condition have been swapped, and the fact that the variable is a char. Lets consider the proper structure of a for loop:

for (initialise variable; for condition; increment variable)
{
      //Do stuff
}

The answer to your question is simple:

  1. Your condition increases i by 1, but as you have pointed out, i is a char. Using operands on a char can convert it to another type, including int (refer C comparison char and int)
  2. A loop will continue until its condition == false.
  3. Your loop will continue running until i=0, which means it will continue to increase by 1 until it reaches 128, at which point it will overflow to -128 and continue to increase until it reaches 0 again.

9 Comments

Read again, In this for loop condition and increment operation is interchanged, OP knows that (she is asking Why this is happening ?)
The question is not "What's better?" it is "Why does this work?" Presumably why does it not go on forever?
@DavidNewcomb it's not apparent to me what the question is
Nutan is asking why this for loop is able to execute. Given the for loop is not written correctly, Nutan's expectation is that it should not execute.
@Nutan, is not running infinitely because it wraps around and at some point i become 0
|
1

Whenever you want to understand for loop in this kind of situation you can convert for loop into while to understand it.

The for syntax is:

for (initialization; condition; operation)
    ...

It can be converted into while as:

initialization; while (condition) { ... operation; }

So in your case

i <= 5 && i >= -1;  // Initialization 
  while(++i) {                //condition
      printf("%d \n", i);
      i > 0;                // operation
  }

Initialization part will be execute once it will check for condition.Here in your case it is ++i so increment every time.Here i>0 means if i==0 then loop will stop it does not matter i is positive or negative Thumb rule to remember in this kind of situation is if (i == 0 ) then true else false. i>0 remains true)in every case after that so loop is infinite. To understand for loop best answer I have seen in SO is this

1 Comment

May I suggest update or something like that instead of increment, for a linked list it's pretty common to write for (node = first ; node != NULL ; node = node->next).
0

There's not rule about the order of for loop condition and increment operation, the latter even don't need to be an increment operation. What it's expected to do is determined by you. The code is just same as the following semantically.

char i = 0;
i <= 5 && i >= -1;     // Run before the loop and only once. No real effect here.
while (++i) {          // Condition used to determine the loop should continue or break
    printf("%d \n", i);
    i > 0;             // Run every time inside the loop. No real effect here.
}

BTW: It'll be an infinite loop (because ++i is a nonzero value until overflow).

1 Comment

The behaviour of ++i when i == CHAR_MAX and plain char is signed, is implementation-defined; and every implementation I know of will define it to give CHAR_MIN

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.