+ 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...
9 ответов
+ 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.
+ 4
But now a question arises,
How is the while loop coded?
+ 4
@Dimis Fajar
Isn't that the already existing Range-Based for loop introduced in C++0x?
+ 4
@Squidy
Thanks a Lot!
+ 3
Thanks a Lot!
+ 3
I want the during loop for yielding values, like a Generator in Python...
+ 3
@conrad wawire
Seriously?
+ 1
then ur a pro. study recursion in c++ first, then give some parameters. build some functional programming of your own. its possible.
- 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;
}