+ 5

How to build a loop function?

Suppose If I want to make a till() or during() loop function for some class type... How would I allow it to execute data below it, like a while or for loop, without using any existing loop functions? Please guide me on this...

27th Mar 2017, 6:25 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
9 odpowiedzi
+ 8
Macros are great for this: #define till(x) while(!(x)) Now you can use it like: int x = 0; till(x == 5) ++x; I'm not sure what logic you have in mind for "during", though. Now if you really want to cut loops out of the picture entirely, you're going to need to use recursion. Write a function that calls itself until a condition is met, and then unwinds. I think you'll need to do this on a case-by-case basis, though. Edit: If you want to know how the while loop is implemented, compile to assembly and look at the machine instructions. If you really want to, you can use inline assembly (the keyword for this depends on your compiler). Note that this will likely bind your program to a specific CPU architecture. The key features will be branch and jump instructions. Here's a macro to mimic a while loop, sort of, but it's not pretty: #define mywhile(x, y) START: if(!(x)) goto END; y; goto START; END: Then use it like: int x = 0; mywhile(x < 5, ++x; std::cout << x; ) That's really the only way to capture a code block.
27th Mar 2017, 6:56 AM
Squidy
Squidy - avatar
+ 4
But now a question arises, How is the while loop coded?
27th Mar 2017, 7:38 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 4
@Dimis Fajar Isn't that the already existing Range-Based for loop introduced in C++0x?
27th Mar 2017, 7:42 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 4
@Squidy Thanks a Lot!
28th Mar 2017, 1:24 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 3
Thanks a Lot!
27th Mar 2017, 7:36 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 3
I want the during loop for yielding values, like a Generator in Python...
27th Mar 2017, 7:43 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 3
@conrad wawire Seriously?
27th Mar 2017, 12:15 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 1
then ur a pro. study recursion in c++ first, then give some parameters. build some functional programming of your own. its possible.
27th Mar 2017, 7:49 AM
Dimas Fajar
Dimas Fajar - avatar
- 1
while loop example #include <iostream> using namespace std; int main () { // Local variable declaration: int a = 10; // while loop execution while( a < 20 ) { cout << "value of a: " << a << endl; a++; } return 0; }
27th Mar 2017, 8:44 AM
Azim Conrad Wawire
Azim Conrad Wawire - avatar