jumping inside loop
C l开发者_开发技巧anguage allows jumping inside loop. What would be the use of doing so?
if(n > 3) {
i = 2;
goto inner;
}
/* a lot of code */
for(i = 0; i < limit ;i ++) {
inner:
/* ... */
}
If you've ever coded in Assembler (ASM), then you'll know that GOTOs are pretty standard, and required, actually. The C Language was designed to be very close to ASM without actually being ASM. As such, I imagine that "GOTO" was kept for this reason.
Though, I'll admit that GOTOs are generally a "bad idea, mmmkay?" in terms of program flow control in C and any other higher level language.
It's certainly a questionable construct. A design that depends on this behavior is probably a poor design.
You've tagged this as C++, but C++ (intelligently, IMO) doesn't allow you to jump inside a loop where a variable was declared in the first part of the for statement:
int main()
{
int q = 5;
goto inner;
for (int i = 0; i < 4; i++)
{
q *= 2;
inner:
q++;
std::cout << q << std::endl;
}
}
g++ output:
l.cpp: In function ‘int main()’: l.cpp:12: error: jump to label ‘inner’ l.cpp:7: error: from here l.cpp:9: error: crosses initialization of ‘int i’
Initializing i
before the loop allows the program to compile fine (as would be expected).
Oddly, compiling this with gcc -std=c99
(and using printf
instead) doesn't give an error, and on my computer, the output is:
6 13 27 55
as would be expected if i
were initialized outside the loop. This might lead one to believe that int i = 0
might be simply "pulled out" of the loop initializer during compilation, but i
is still out of scope if tried to use outside of the loop.
From http://en.wikipedia.org/wiki/Duff%27s_device
In computer science, Duff's device is an optimized implementation of a serial copy that uses a technique widely applied in assembly language for loop unwinding.
...
Reason it works
The ability to legally jump into the middle of a loop in C.
精彩评论