Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Multiple exit conditions in for loop (multiple variables): AND -ed or OR -ed?

Tags:

For loops and multiple variables and conditions.

I am using a for loop to set source and destination indexes to copy items in an array.

for(int src = 0, dst = 8;     src < 8, dst >= 0;     src ++, dst --) {     arr2[dst] = arr1[src]; } 

Something like that anyway.

(AND) || (||)

My question is about the exit conditions. There are two here. src < 8 and dst >= 0. Are these conditions AND-ed (&&) or OR-ed (||).

To further explain, are the conditions evaluated like this:

(src < 8) && (dst >= 0) 

Or are they evaluated like this?

(src < 8) || (dst >= 0) 

Or is it something else entirely different? I imagine the logical thing to do would be to evaluate one of the two ways I specified above, and not something else.

like image 689
FreelanceConsultant Avatar asked Aug 05 '13 16:08

FreelanceConsultant


People also ask

Can you have 2 conditions in a for loop in C?

Note: both are separated by comma (,). 2. It has two test conditions joined together using AND (&&) logical operator. Note: You cannot use multiple test conditions separated by comma, you must use logical operator such as && or || to join conditions.

How do you put multiple conditions in a for loop?

It do says that only one condition is allowed in a for loop, however you can add multiple conditions in for loop by using logical operators to connect them.

Can you declare 2 variables in for loop?

Yes, I can declare multiple variables in a for-loop. And you, too, can now declare multiple variables, in a for-loop, as follows: Just separate the multiple variables in the initialization statement with commas. Do not forget to end the complete initialization statement with a semicolon.

Can you Increment 2 variables in a for loop?

Incrementing two variables is bug prone, especially if you only test for one of them. For loops are meant for cases where your loop runs on one increasing/decreasing variable. For any other variable, change it in the loop.


1 Answers

The comma operator will return the value of the right expression, so writing this:

 src < 8, dst >= 0; 

As a condition will be the same as just writing dst >= 0. The src < 8 will be completely ignored in this case, as it's evaluated separately from the second condition, and then the second condition is returned. This doesn't evalute to AND or to OR, but in fact just has the effect of "throwing away" the first check entirely.

If you want to evaluate this correctly, you should use one of your two options (explicitly specifying the behavior via || or &&).

For details, see Comma Operator:

When the set of expressions has to be evaluated for a value, only the rightmost expression is considered.

like image 56
Reed Copsey Avatar answered Oct 21 '22 10:10

Reed Copsey