是否可以将标签的地址存储在变量中并使用 goto 跳转到它? [英] Is it possible to store the address of a label in a variable and use goto to jump to it?

查看:25
本文介绍了是否可以将标签的地址存储在变量中并使用 goto 跳转到它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道每个人都讨厌 goto.在我的代码中,出于我考虑过并感到满意的原因,它们提供了一个有效的解决方案(即我不是在寻找不要这样做"作为答案,我理解您的保留意见,并理解我为什么要使用它们反正).

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.

如果此代码有效,它将代表我需要的功能类型.但它不起作用,30 分钟的谷歌搜索没有发现任何东西.有人有什么想法吗?

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;
}

推荐答案

C 和 C++ 标准不支持此功能.但是,GNU Compiler Collection (GCC) 包含一个非标准扩展来执行此操作,如 这篇文章.本质上,他们添加了一个特殊的运算符&&"将标签的地址报告为void*"类型.详情见文章.

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.

附言换句话说,只需使用&&"而不是&"在您的示例中,它将适用于 GCC.
P.P.S.我知道你不想让我说,但我还是要说,...不要那样做!!!

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!!!

这篇关于是否可以将标签的地址存储在变量中并使用 goto 跳转到它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆