Using Goto function across different functions

2019-02-21 09:09发布

How can I use goto function across different functions .For ex ,

    main()
    {
      ....
      REACH:
      ......
    }

    void function()
    {
    goto REACH ;
    }

How to implement such usage ?

标签: c++ c goto
3条回答
三岁会撩人
2楼-- · 2019-02-21 09:23

You can't in Standard C++. From $6.6.4/1 of the C++ Language Standard

The goto statement unconditionally transfers control to the statement labeled by the identifier. The identifier shall be a label (6.1) located in the current function.

...or in Standard C. From $6.8.6.1/1 of the C Language Standard

The identifier in a goto statement shall name a label located somewhere in the enclosing function. A goto statement shall not jump from outside the scope of an identifier having a variably modified type to inside the scope of that identifier.

查看更多
女痞
3楼-- · 2019-02-21 09:25

You can't in Standard C; labels are local to a single function.

The nearest standard equivalent is the setjmp() and longjmp() pair of functions.

GCC has extensions to support labels more generally.

查看更多
Bombasti
4楼-- · 2019-02-21 09:29

For gcc:

#include <iostream>

void func(void* target){
    std::cout << "func" <<std::endl;
    goto *target;
}


int main() {
    void* target;
    auto flag = true;
l:
    std::cout << "label" <<std::endl;
    target = &&l;
    if (flag) {
        flag = false;
        func(target);
  }
}

Note that this can be an undefined behavior

查看更多
登录 后发表回答