![](/img/trans.png)
[英]Can somebody help on how to return each array in function and then calling it all at main function? [c]
[英]How to return to main and not the function calling it?
我有一个function()
,它调用anotherFunction()
。 在anotherFunction()
内部,有一个if
语句,当满足时,该语句将返回main()
而不是function()
。 你怎么做到这一点?
您无法在“标准” 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
或通过指针返回(如果该函数已用于返回其他内容)
您可以使用setjmp和longjmp函数绕过C中的正常返回序列。
他们在Wikipedia上有一个例子:
#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;
}
在C语言中,您不容易做到这一点。最好的选择是从anotherFunction()
返回状态代码,并在function()
中进行适当处理。
(在C ++中,您可以使用异常有效地实现所需的功能)。
大多数语言都具有启用此类流控制的异常 。 C没有,但是它确实具有setjmp
/ longjmp
库函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.