2014-12-05 67 views
-1

我有一个function(),它调用anotherFunction()。 在anotherFunction()里面,有一条if语句,当满足时返回main()而不是function()。你怎么做到这一点?谢谢。如何返回主,而不是调用它的函数

+0

@mafso通过返回一个指针:啊,你说得对。标准中提到“初始调用main()'”暗示可能有其他的。 – 2014-12-05 17:03:30

回答

2

您可以用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; 
} 
1

你不能轻易做,在C.你最好的赌注是从anotherFunction()返回状态代码和function()处理该适当。

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

+0

这是不正确的。标准的setjmp和longjmp提供了这个功能。 – b4hand 2014-12-05 17:06:26

+1

我想这很容易*。我不喜欢存储缓冲区。我真的不会推荐它,并坚持使用返回码的建议。 – Bathsheba 2014-12-05 17:07:33

1

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

5

在“标准”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或者如果该功能已经被用来返回别的东西

+0

@Bathsheba它可能在某些情况下有用,但在这种情况下不会有用,因为有更简单和更安全的解决方案 – 2014-12-05 16:56:45

+2

setjmp和longjmp都是标准C,因为您甚至可以引用它们。 – b4hand 2014-12-05 16:59:29

相关问题