I have this code:
int i = 0, j = 0;
for(i=0,j=0;i<5,j<25;i++,j++);
cout<<i <<" "<<j;
And I don’t know why it outputs 25 25. I really don’t understand why its getting the value 25 in i and j. Can any one please explain me why it is reaching value 25 from the second condition? Is this the problem of checking the two condition in one for loop?
This is the effect of the comma operator. This means it ignores the first argument of the test and returns the 2nd for the test result.
Since you have semicolon (
;) at the end of your loopyour for-loop executes “silently” all the way through (only considering the
j<25condition) and when it is done, the value for both variables is25.If you want to see the output while the loop is executing to verify this, remove the
;from the end of theforstatement.If you wanted to terminate the loop based on the values of both
i < 5andj < 25you probably want to use the&&(and) operator.