No expressions or declarations are allowed only.
EDIT: Sorry. I thought you were talking about the state of a part of the loop. In the expression part of the loop, only expressions are allowed.
You can use a lambda expression that will contain this for the loop. for example
for ( i = 1; i <= N; []( int i ) { for ( j = 1; j <= i; j++, printf("%c", '0' ) ); }( i ), i++)
Here is a demo
#include <iostream> int main() { int N = 10; for ( int i = 1; i < N; []( int i ) { for ( int j = 1; j < i; j++, ( std::cout << '*' ) ); }( i ), i++ ) { std::cout << std::endl; } return 0; }
Output signal
* ** *** **** ***** ****** ******* ********
Or you can define a lambda expression outside the outer loop to make the program more readable. for example
#include <iostream> int main() { int N = 10; auto inner_loop = []( int i ) { for ( int j = 1; j < i; j++, ( std::cout << '*' ) ); }; for ( int i = 1; i < N; inner_loop( i ), i++ ) { std::cout << std::endl; } return 0; }
Note that in general, nested loops shown in other posts cannot replace a loop with a lambda expression. For example, the outer loop may contain continue statements that will skip the inner loop. Therefore, if you want the inner loop to be executed in any case, regardless of the continue statements, this construction with a lambda expression will be useful. :)
Vlad from Moscow Sep 07 '14 at 17:16 2014-09-07 17:16
source share