Saturday 4 April 2020

goto Statement in C++


It allows making an absolute jump to another point in the program. You should use this feature carefully since its execution ignores any type of nesting limitation.
The destination point is identified by a label, which is then used as an argument for the goto instruction. A label is made of a valid identifier followed by a colon (:).
This instruction does not have a concrete utility in structured or object oriented programming aside from those that low-level programming fans may find for it. For example, here is our countdown loop using goto:

// goto loop example

#include <iostream.h>
int main ()
{
  int n=10;
  loop:
  cout << n << ", ";
  n--;
  if (n>0) goto loop;
  cout << "FIRE!";
  return 0;
}

Output:
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!

No comments:

Post a Comment