CSJ
CSJ

Reputation: 2957

Condition in for loop of C

Today I made a typo, and then found below code can be compiled successfully:

#include <stdio.h>
int main()
{
    int i;
    for (i=0;1,2,3,4,5;i++)
        printf("%d\n", i);
}

I don't understand why

1,2,3,4,5

can be treated as a condition?

Upvotes: 2

Views: 136

Answers (7)

vinay hunachyal
vinay hunachyal

Reputation: 3891

Yes. As others say it's .always true and the comma operator yields 5, hence the loop will repeat infinite times

You can verify it by replacing 5 with 0 . Like this 1,2,3,4,0

Here 0 is false, hence the condition fails.

Upvotes: 1

VenkatKrishna
VenkatKrishna

Reputation: 127

// try to know the meaning of condition.

#include <stdio.h>
int main()
{
  int i=0;
  if(i<=5) // try this
  {
    printf("%d\n",i); 
    i++;   // increment i 
  }

}

Upvotes: -2

CiaPan
CiaPan

Reputation: 9571

A for loop:

for( E1; E2; E3 )
  IB

with expressions E1, E2, E3 and an instruction IB is equivalent to a while loop:

E1;
while( E2 )
{
    IB;
    E3;
}

The only exception is E2, which must be present in while loop condition whilst may be omitted in a forloop condition (and then it is considered equal 1).

So, as others already said, your 1,2,3,4,5 is a comma expression equivalent to a constant 5, making the loop looping infinitely.

Upvotes: 0

Sagar Jain
Sagar Jain

Reputation: 7941

Yes, 1,2,3,4,5 can be treated as a condition.

The output of 1,2,3,4,5 is 5.

In fact, you need not specify any condition in for loop.

for(;;) is a valid syntax.

Upvotes: 0

SpeedJack
SpeedJack

Reputation: 139

See that this code runs... but the for loop continues indefinitely. The condition 1,2,3,4,5 is always verified. The compiler accepts more that one conditions in for loops. For example:

for(i=0, j=0; i<X, j>y; i++, j--)
    //.....

So 1,2,3,4,5 are five conditions (not one) and all these conditions are verified (in fact, these numbers are all different from 0 so they're always true).

Upvotes: -1

nd.
nd.

Reputation: 8932

Your for condition is the expression 1,2,3,4,5. This expression is evaluated using C's comma operator and yields 5. The value 5 is a valid boolean expression that is true, therefore resulting in an infinite loop.

Upvotes: 5

Daniel Daranas
Daniel Daranas

Reputation: 22624

You are using the comma operator. The value of 1, 2, 3, 4, 5 is 5.

More generally, the value of a, b is b. Also, the value of f(), g() is the return value of g(), but both subexpressions f() and g() are evaluated, so both functions are called.

Upvotes: 3

Related Questions