Question:
Multiple test & update expressions in "for" loops? (C++)?
Grace
2017-11-09 14:19:04 UTC
I know I can have multiple initialization expressions, but can I have multiple test & update expressions as well?

Thanks
Four answers:
Chris
2017-11-09 17:54:49 UTC
It wasn't worded perfectly, but the question is pretty clear. Why not just answer it, instead of droning on how it's only a single statement? Who cares?



Multiple tests have to be turned into a single expression. This is done using && and ||, just like in any other situation where you test multiple things.



In the update part, you can also have multiple updates by again separating them with a comma.



for (i = 1, j = 20; i <= 10 && j > 0; i++, j--)



https://ideone.com/anK8cH
bocephusmcguire
2017-11-09 16:44:52 UTC
Husoki and Oyubir handled the notion of "multiple initialization" pretty thoroughly. Let me add the following regarding "multiple test". You could use Boolean operators to perform multiple test, to wit:



int test(int);

for (int i=0; i<40 && test(i); i++) ;



So in this example you have tested i<40 AND the result of the function call.
husoski
2017-11-09 16:08:40 UTC
You get a single expression or a single declaration in the initialization part of a for statement--exactly one of those, and not both. What looks like "multiple statements" to you are either use of the comma operator, as in:



for (i=0, j=10; i


...or declaring multiple variables in a single declaration, as in:



for (int i=0, j=10; i


Neither one of those use "multiple statements". The comma operator takes two expressions and returns the right one as a result. The left expression is only evaluated for side-effects, like assignments and increments. Unlike most operators, the comma guarantees evaluating the left expression before the right.



Using a declaration is a bit similar. Just like in a declaration statement, a declaration in a for statement can defined and initialize multiple variables. They all must be the same type, though. That's important. The following is invalid:



for (int i=0, long isq = (long)i*i; i<10000; ++i, isq=i*i)



There's nothing like that in the for statement syntax. You need to move one or both of the declarations outside of the for statement.



You can use comma operators in the other parts of the for statement header (test and increment) but not declarations. For example, the first two examples above use commas to get both i and j updated in the increment part.
?
2017-11-09 14:20:07 UTC
acii port


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...