Very strange goto

1
2
3
4
5
6
7
8
9
10
#include <conio.h>

int main()
{

int i;
goto *i; // yes, it compiles! And crashes...

getch();
}

anyone can explain what's goin on? I'm just curious...
IMO that shouldn't compile >_> ...what compiler are you using?
GCC on windows. Try to compile yoursel!
Why are you trying to goto a pointer dereference? I'm confused...
Looks like a GCC bug. It fails under Microsoft and Sun compilers.
That is a GCC extension, called a "computed goto".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// This example only works with the GCC!
//
// Also, it uses goto gratuitously -- this would have been
// better (and easier) done with any other control construct.

#include <iostream>
#include <limits>
using namespace std;

int main()
  {
  void* computed_goto;

  int age;
  cout << "How old are you? " << flush;
  cin >> age;
  cin.ignore( numeric_limits <streamsize> ::max(), '\n' );

  if      (age <  21) computed_goto = &&too_young;
  else if (age >= 65) computed_goto = &&too_old;
  else                computed_goto = && just_right;

  goto *computed_goto;

  too_young:
    cout << "You're too young!\n";
    goto the_end;

  too_old:
    cout << "You're too old!\n";
    goto the_end;

  just_right:
    cout << "Hello!\n";

  the_end:
    cout << "Press ENTER to quit..." << flush;
    cin.ignore( numeric_limits <streamsize> ::max(), '\n' );

  return 0;
  }

This feature exists for the creation of jump tables... See section 5.3 of the latest GCC documentation. (And for better examples of how to use it in a jump table.)

Hope this helps.
Just when you thought goto's couldn't get any worse!

I guess it's providing one less reason to use assembly language in some special circumstance.
That sounds like a silly addition. Wouldn't assigning to a variable and using a switch do the same and be more readable?
Topic archived. No new replies allowed.