+ 1

a loop inside a variable

how do I store a loop or function inside a variable? For example... What if I wanted to take this for loop with rand() int main () { for (int x = 0; x <= 10; x++) { cout << 2+ (rand() % 8) << endl; } } store it inside a variable and print the variable?

8th Feb 2017, 8:30 PM
Mich
Mich - avatar
4 Answers
+ 8
You can store the whole thing as a string and print it. It won't loop for you though...
8th Feb 2017, 9:20 PM
Jafca
Jafca - avatar
+ 5
the closest thing i can think of is something like this: https://code.sololearn.com/cdGoZJCwei1z/#cpp further reading: http://www.cprogramming.com/tutorial/function-pointers.html
8th Feb 2017, 10:12 PM
Burey
Burey - avatar
+ 4
What you want is a C++ lambda. You can create the loop inside a function (code block) and then assign that function to the lambda. Note that this requires you to use a C++11 or greater compiler. lambda example: auto func = [](){ for (int x = 0; x <= 10; x++) { cout << 2+ (rand() % 8) << endl; } }; func(); calls the func lambda
8th Feb 2017, 10:29 PM
ChaoticDawg
ChaoticDawg - avatar
+ 2
Thank you guys
10th Feb 2017, 12:29 PM
Mich
Mich - avatar