【问题标题】:How to return to main and not the function calling it?如何返回 main 而不是调用它的函数?
【发布时间】:2014-12-05 16:50:22
【问题描述】:

我有一个function(),它调用anotherFunction()。 在anotherFunction() 内部,有一个if 语句,当满足时返回main() 而不是function()。你是怎么做到的?

【问题讨论】:

  • @mafso:啊,你是对的。该标准谈到“对main() 的初始调用”暗示可能还有其他人。

标签: c function control-flow setjmp


【解决方案1】:

您不能在“标准”C 中这样做。您可以使用 setjmplongjmp 实现它,但强烈建议不要这样做。

为什么不直接从anotherFuntion() 返回一个值并基于该值返回?像这样的

int anotherFunction()
{
    // ...
    if (some_condition)
        return 1; // return to main
    else
        return 0; // continue executing function()
}

void function()
{
    // ...
    int r = anotherFuntion();
    if (r)
        return;
    // ...
}

你可以返回_Bool,如果函数已经被用来返回别的东西,你可以通过指针返回

【讨论】:

  • @Bathsheba 在某些情况下可能有用,但在这种情况下则不然,因为有更简单、更安全的解决方案
  • setjmp 和 longjmp 都是标准 C,因为您甚至引用了它们。
【解决方案2】:

在 C 中你不能轻易做到这一点。最好的办法是从 anotherFunction() 返回一个状态代码,并在 function() 中适当地处理它。

(在 C++ 中,您可以使用异常有效地实现您想要的)。

【讨论】:

  • 这是不正确的。标准的 setjmp 和 longjmp 正好提供了这个功能。
  • 我想这归结为很容易。我不喜欢必须存储缓冲区。我真的不推荐它,并坚持我使用返回码的建议。
【解决方案3】:

大多数语言都有例外可以实现这种流控制。 C 没有,但它确实具有执行此操作的 setjmp/longjmp 库函数。

【讨论】:

    【解决方案4】:

    您可以使用 setjmp 和 longjmp 函数绕过 C 中的正常返回序列。

    他们在维基百科上有一个例子:

    #include <stdio.h>
    #include <setjmp.h>
    
    static jmp_buf buf;
    
    void second(void) {
        printf("second\n");         // prints
        longjmp(buf,1);             // jumps back to where setjmp was called - making setjmp now return 1
    }
    
    void first(void) {
        second();
        printf("first\n");          // does not print
    }
    
    int main() {   
        if ( ! setjmp(buf) ) {
            first();                // when executed, setjmp returns 0
        } else {                    // when longjmp jumps back, setjmp returns 1
            printf("main\n");       // prints
        }
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多