Using goto statements is usually proclaimed a terrible idea by programmers, teachers, etc. etc. And usually it is. I haven't come across a problem yet in C or C++ (or any other high-level language) that NEEDED goto statements - it's always been a loop, or a function, or something like that. I'll repeat: as far as I know, YOU DO NOT NEED GOTO STATEMENTS.
That being said, when your code is compiled, all that exists are goto statements in some form or another. That's all a loop is: a fancy, dressed up goto: statement with extra checks and assignments. So sometimes you can use goto: statements explicitly in order to speed your code up.
If you are a beginner programmer, or even a programmer not too interested in minimal time gains/optimization, then ignore the existence of goto.
for (...) { // work on first dimension
for (...) { // work on second dimension
for (... { // work on third dimension
do {
if ( x < y) goto trouble;
...
trouble:
stderr << "Earth goes boom";
return 99;
The goto makes escape quick and easy, not requiring a series of if/break in each loop.
Sorry, did not mean to imply that goto was the work of the devil and should never be used, hence the smiley.
Let me clarify; the goto statement performs an unconditional transfer of control to the named label and as such should be treated with care. It is good programming style to use the break, continue, and return statement in preference to goto whenever possible. As the break statement only exits from one level of a loop, a goto may be necessary ‘bust out’ of a deeply nested loop.
cleveland2000
You should start a new topic but : http://www.cplusplus.com/reference/clibrary/cstdlib/srand.html
As far as I know, non-local exits using goto or setjmp/longjmp (in C) can bypass any cleanup so they're a prime candidate for causing memory leaks and runtime errors. It's much better to throw and catch an exception in C++:
1 2 3 4 5 6 7 8 9 10 11 12
struct trouble;
try{
for (...) { // work on first dimension
for (...) { // work on second dimension
for (... { // work on third dimension
do {
if ( x < y) throw(trouble);
...
} catch (trouble) {
stderr << "Earth goes boom";
return 99;
}
@arnaudk
That is a common abuse of exception handling, using exceptions as an alternative flow control mechanism. Don’t do it! It will only make the code harder to read. It will also make your code slower to execute as throwing exceptions are generally an expensive operation.