Reshad
Reshad

Reputation: 239

How does this C++ while loop work?

I learned the basics of C++ few months ago. Recently I found a while loop that looks like this. I want to understand how it works.

while(cin>>n>>m,n||m)
{
    does something;
}

Upvotes: 1

Views: 129

Answers (3)

Shrikanth N
Shrikanth N

Reputation: 652

The second parameter in the expression with comma is your condition. So it will evaluate the loop based on n||m where n and m are values read as inputs.

cin>>n>>m;  //Read values of n and m
while(n||m) //Check if n OR m is true
{
    does something;
    cin>>n>>m; //Read the next set of values
};

Upvotes: 0

Reshad
Reshad

Reputation: 239

as long as both n and m is not equal to zero the loop will run every time it will at first execute the cin>>n>>m and then check the condition n||m

Upvotes: 0

LibertyPaul
LibertyPaul

Reputation: 1167

operator , (operator comma) executes all instructions in list and returns value of last expression, so cin>>n>>m,n||m is equal to

cin >> n >> m;
n || m;

And whole loop will work like this one:

int n, m;
cin >> n >> m;
while(n || m){
    //some action
    cin >> n >> m;
}

Upvotes: 5

Related Questions