Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a for loop have an assignment in its statement?

Tags:

I came upon this syntax

for (string st; getline(is, st, ' '); v.push_back(st));          ^                  ^                  ^     initialization   condition, increment    ??? 

How does the v.push_back(st) work as an increment when that's being covered by getline(is, st, ' ')?

like image 335
Strahinja Ajvaz Avatar asked Nov 03 '15 11:11

Strahinja Ajvaz


1 Answers

That's equivalent to:

for (string st; getline(is, st, ' '); )     v.push_back(st); 

or:

{     string st;     while (getline(is, st, ' '))         v.push_back(st); } 

The fact is that the increment statement is executed at the end of the body of the loop every time the condition is fulfilled. So, you can see it as the very last instruction of the body.

Sometimes, you may leave the increment statement empty; in this case, you put the only instruction of the body in place of the increment statement.

like image 171
Paolo M Avatar answered Oct 19 '22 00:10

Paolo M