Goto statement confusion

Hey this is my second forum of the day. I hope that's cool, not trying to flood traffic. ANyway I'm confused by two things in this websites example of a go to statement.
1
2
3
4
5
6
7
8
9
10
11
12
  #include <iostream>
using namespace std;

int main ()
{
  int n=10;
mylabel: //what is my label and what is the colon for?
  cout << n << ", ";
  n--;
  if (n>0) goto mylabel; //is my label like a variable or a type?
  cout << "liftoff!\n";
}
Firstly, goto is widely advised against, secondly, mylabel is just basically a marker in the program that can be seen by goto statements, it doesn't do anything else. That is why it has to colon, it lets the compiler no it is a label not a variable. The goto statment is fairly unique and is the keyword goto followed by the name of a label placed somewhere else in the program, it then carries on the program from that label. This is one (strongly advised against) way of making a loop.
Are you like the god of C++? thanks for your help again :D
Why is it so strongly advised against?
Because in most cases it is possible to reorganize the code using gotos in a structured fashion, and the resulting code is much more readable.

For example, the code above would be much shorter if a for loop had been used instead of goto. Also, it would make the code easier to read and understand.
Last edited on
To illustrate what's been said, here's a version of your program which uses a "for" loop, instead of a goto:

1
2
3
4
5
6
7
8
9
10
#include <iostream>
int main ()
{
    for (int i=10; i>=0; i--)
    {
        std::cout << i << ", ";
    }
    std::cout << "liftoff!\n";
    return 0;
}

It also forgoes the use of "using namespace std;" (which isn't a huge deal in such a small, simple program, but as a general rule it's best not to get into the habit of automatically putting a "using namespace std;" at the top of all your code without even a moment's thought) and I slapped on a "return 0;" at the end of main().
Topic archived. No new replies allowed.