Is it possible to store the address of a label in

2019-01-21 05:49发布

I know everyone hates gotos. In my code, for reasons I have considered and am comfortable with, they provide an effective solution (ie I'm not looking for "don't do that" as an answer, I understand your reservations, and understand why I am using them anyway).

So far they have been fantastic, but I want to expand the functionality in such a way that requires me to essentially be able to store pointers to the labels, then go to them later.

If this code worked, it would represent the type of functionality that I need. But it doesn't work, and 30 min of googling hasn't revealed anything. Does anyone have any ideas?

int main (void)
{
  int i=1;
  void* the_label_pointer;

  the_label:

  the_label_pointer = &the_label;

  if( i-- )
    goto *the_label_pointer;

  return 0;
}

14条回答
兄弟一词,经得起流年.
2楼-- · 2019-01-21 06:20

The C and C++ standards do not support this feature. However, the GNU Compiler Collection (GCC) includes a non-standard extension for doing this as described in this article. Essentially, they have added a special operator "&&" that reports the address of the label as type "void*". See the article for details.

P.S. In other words, just use "&&" instead of "&" in your example, and it will work on GCC.
P.P.S. I know you don't want me to say it, but I'll say it anyway,... DON'T DO THAT!!!

查看更多
在下西门庆
3楼-- · 2019-01-21 06:20

The only officially supported thing that you can do with a label in C is goto it. As you've noticed, you can't take the address of it or store it in a variable or anything else. So instead of saying "don't do that", I'm going to say "you can't do that".

Looks like you will have to find a different solution. Perhaps assembly language, if this is performance-critical?

查看更多
登录 后发表回答