[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CppGoto
You can only jump to the same code block you jump from:
Using goto is considered bad programming practice [1-2], the use of for and while is more appreciated. The active use of goto results in code that is called spaghetti code.
You could use goto when you want to end multiple loops, as the break command only breaks one loop.
Avoid goto [1,2]
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
CppGoto
(C++) goto
keyword enabling you to make jumps in your code.You can only jump to the same code block you jump from:
void func1()
{
goto labelFunc2; //Error: Undefined label 'labelFunc2'
}
void func2()
{
labelFunc2:
}
Using goto is considered bad programming practice [1-2], the use of for and while is more appreciated. The active use of goto results in code that is called spaghetti code.
You could use goto when you want to end multiple loops, as the break command only breaks one loop.
int myFunction() { return std::rand()%1000; } int main() { const unsigned int maxy = 1000; const unsigned int maxx = 1000; const unsigned int maxz = 1000; for (unsigned int z=0; z<maxz; ++z) { for (unsigned int y=0; y<maxy; ++y) { for (unsigned int x=0; x<maxx; ++x) { std::cout << "x: " << x << ",y: " << y << ",z: " << z << std::endl; if (myFunction()==0) goto afterloop; } } } afterloop: std::cout << "Done. " << std::endl; return 0; }
- include <iostream>
Avoid goto [1,2]
Code links
'goto' links
References
- 1) Bjarne Stroustrup. The C++ Programming Language (3rd edition).ISBN: 0-201-88954-4 6.5.8: 'Avoid goto'
- 2) Jesse Liberty. Sams teach yourself C++ in 24 hours. ISBN: 0-672-32224-2. Hour 6, paragraph 'Why goto isn't used': 'The indiscriminate use of goto statements has caused tangled, miserable, impossible-to-read programs known as spaghetti code'
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
