Regeneration with goto
Written by leezy_2000
I remember that when I started learning C, the teachers and textbooks have a moon: "Don't use the GOTO statement, otherwise it will lead to extremely decline in program readability. But it can greatly improve efficiency, can be used." I am active, but I have to think about it, Goto once I was thrown into the trash. Later, as the reading code increased, I found that GOTO can improve the program in two ways. First, the error is handled, and the other is used to imitate recursive. Used to make a wrong handling, in some specific occasions, enhance reading. Used to simulate recursive, greatly improve the performance of the program, but will undoubtedly reduce the readability of the program. This article discusses the latter.
Let's see a code:
Seeking all integers within the range of N-0.
Unsigned add (unsigned num)
{
IF (NUM! = 0) Return Num Add (NUM-1);
Else Return 0;
}
When using:
Unsigned c = 100;
COUT << Add (c) << endl;
This program is simple, just use the recursive solution, nothing to say. Of course, the efficiency is not high, especially when NUM is relatively large. This effect is caused by excessive frequent function calls.
Now let's spend the characteristics of this recursive call:
1. Since the recursive function prototype is consistent, the data type stored in the stack is consistent. That is, it is equivalent to an array.
2. Press the stack, grow the stack size, reach a critical condition and start the stack. And accumulate the stack data. The number of outlets is of course the same number of stacks.
In order to reduce the impact of the function call to performance, let's simulate this process. See the following procedures and comments.
Unsigned stack [100]; // Simulate stack, assume N to 100
Bool goback = false; // critical condition
INT i = 0; // count
INT P = C; // p = 100
INT NUM = 0; //
// Entrance to the recursive function
Recurse:
IF (p! = 0) // into the stack
{
Stack [i ] = p -;
Goto recurse;
}
Else GOBACK = true; // reaches critical conditions
// Find, seek, return from recursion
IF (--i> = 0)
{
Num = stack [i];
Goto recurse;
}
This is achieved, there is better improvement in space and time, of course, the premise is to use in the appropriate place.
Last explanation, this method is not my invention. Qsort in the Microsoft C / C runtime library is implemented in this way.