Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot understand for loop with two variables [duplicate]

When I use two variables in a for loop with different conditions two conditions like I have used below i<3,j<2 the for loop is always executing till the second condition fails.

#include<iostream>
#include<conio.h>
using namespace std ;
int main()
{
int i,j ;
for(i=0,j=0;i<3,j<2;i++,j++)
{
    cout<<"hello" ;
}
getch() ;
return 0 ;
} 

In that code, hello is printed 2 times. Why?

If I use i<3,j<10, "Hello" is printed 10 times. I can't understand why the first condition is being neglected. Is it compiler dependent or something else?

Every thing works normal if I replace with conditions like || (OR) or &&(AND).An other thing is that I cannot initialize i and j in the for loop itself, it is showing me an error, but works fine when I declare variables in C style or one variable outside the for loop, why is it so?

Compiler I have used is Orwell Dev C++.
Thanks in advance.

like image 791
Arun Avatar asked Oct 05 '13 05:10

Arun


1 Answers

for(i=0,j=0;i<3,j<2;i++,j++)

is equivalent to

for(i=0,j=0;j<2;i++,j++)

The comma expression takes on the value of the last expression.

Whichever condition is first, will be disregarded, and the second one will be used only.

like image 112
P0W Avatar answered Sep 30 '22 04:09

P0W