我有一个function()
which 调用anotherFunction()
。里面anotherFunction()
有一个if
语句,当满足时返回main()
而不是返回function()
。你怎么做到这一点?
问问题
129 次
4 回答
5
您不能在“标准”C 中这样做。您可以使用setjmp和longjmp实现它,但强烈建议不要这样做。
为什么不只返回一个值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
如果该函数已用于返回其他内容,则可以通过指针返回或返回
于 2014-12-05T16:55:01.703 回答
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;
}
于 2014-12-05T16:54:09.823 回答
2
在 C 中你不能轻易做到这一点。最好的办法是anotherFunction()
从function()
.
(在 C++ 中,您可以使用异常有效地实现您想要的)。
于 2014-12-05T16:54:23.740 回答
2
大多数语言都有启用这种流控制的例外。C 没有,但它确实具有执行此操作的setjmp
/longjmp
库函数。
于 2014-12-05T16:54:32.760 回答