2

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?

Daniel Daranas
  • 22,454
  • 9
  • 63
  • 116
CSJ
  • 2,709
  • 4
  • 24
  • 30

7 Answers7

5

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.

Community
  • 1
  • 1
nd.
  • 8,699
  • 2
  • 32
  • 42
3

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.

Daniel Daranas
  • 22,454
  • 9
  • 63
  • 116
1

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.

Cjmarkham
  • 9,484
  • 5
  • 48
  • 81
vinay hunachyal
  • 3,781
  • 2
  • 20
  • 31
0

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.

Sagar Jain
  • 7,475
  • 12
  • 47
  • 83
0

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.

CiaPan
  • 9,381
  • 2
  • 21
  • 35
-1

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).

SpeedJack
  • 139
  • 2
  • 8
  • 1
    Wrong, this is one condition. Evaluating of 1 through 4 does not affect evaluating of 5, which solely defines the final value of a condition. Note the difference between comma operator `,` and boolean `&&` operator. – CiaPan Aug 01 '14 at 10:17
-2

// 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 
  }

}
VenkatKrishna
  • 127
  • 3
  • 11