1
for (int i = 0 ; i < 10 ; ++i)
{
    for (int j = 0 ; j < 10 ; ++j)
    {
        goto label;
    }
}
label:
// stuff

After goto will the i and j variables get freed? From what I recall goto doesn't unwind the stack or do any cleanup so will it screw something up in this case?

NPS
  • 6,003
  • 11
  • 53
  • 90
  • 2
    Do you need `goto`? If you need the above function, add it in a function and use `return` – Karthik T Aug 07 '13 at 10:34
  • 2
    NEVER EVER use `goto`. Also you could check this for your self pretty easily. – Jori Aug 07 '13 at 10:35
  • @Jori, `goto` has its place, but here, a function is probably best. – chris Aug 07 '13 at 10:37
  • 1
    This is one of the few cases where I find `goto` useful. The `break` keyword doesn't _break_ out of nested loops. – Blastfurnace Aug 07 '13 at 10:37
  • 1
    @Jori sometimes goto is appropriate to exit nested loops. – Neil Kirk Aug 07 '13 at 10:37
  • @Blastfurnace But `break` is just a goto in disguise. You need it for the cases in a switch, but otherwise, it is best avoided as well. As a general rule: `goto` and `continue`: never, `break`: only to end a case in a switch; `return` only as the last statement of a non-void function. (There are a few exceptions, particularly with regards to the return, but overall, if you feel the need to violate the above rules, you've not thought the algorithm out thoroughly, or you've not broken the functions down enough.) – James Kanze Aug 07 '13 at 11:43
  • @JamesKanze These are terrible rules. – NPS Aug 07 '13 at 11:46
  • @NPS Unless you're trying to write code that actually works, reliably. – James Kanze Aug 07 '13 at 11:54
  • @JamesKanze Honest to God, what possible argument could you have against stopping execution of code earlier (in some cases only, of course) with `continue`, `break` or `return`? – NPS Aug 07 '13 at 12:02
  • @NPS Just that it's impossible to reason about the code if you do. This is not a new concept; it was first argued by Dijkstra, 30 or 40 years ago. – James Kanze Aug 07 '13 at 14:25
  • `goto` has no place in clean code. Its perhaps sometimes useful to speed things up, but in the end you end up with sloppy code. There is NO excuse for `goto`. – Jori Aug 07 '13 at 16:04
  • @JamesKanze Care to elaborate? Links/sources would be nice. – NPS Aug 07 '13 at 20:48
  • The reference is _Structured Programming_, Dahl, Dijkstra and Hoare (ISMB 0-12-200550-3), despite its date (1972) still one of the most important texts a programmer should have studied. – James Kanze Aug 08 '13 at 08:03

1 Answers1

3

Yeah, it gets cleaned up. Because C++ frees variables that go out of scope.

Bhargav Ponnapalli
  • 9,224
  • 7
  • 36
  • 45