gpt4 book ai didi

c - 如何在C中实现return *语句?

转载 作者:行者123 更新时间:2023-12-02 19:37:45 25 4
gpt4 key购买 nike

我正在阅读有关递归上升-下降解析器的文章 here

在第 2.1 节中,他们描述了一个 return * 语句,

Our C extension occurs with return statements. We have used the notation return * k to indicate that a k-level function return is to be made. That is, return * 1 is identical to the normal C return statement and simply returns control to the caller of the current function; return * 2 means that control is to be returned to the caller of the caller, and so on. Finally, return * 0 is to be interpreted as a null statement. We leave emulation of the return * k construct in languages that lack this operation as a simple exercise for the reader.

如何在自己的代码中实现此类 return* 语句或使用 goto 语句或/和指针模拟此行为?是否有任何语言默认提供此功能?

最佳答案

您可以使用setjmp()longjmp()来模拟这种多级返回,只要您注意维护一个jmp_buf堆栈s 每次调用函数时。

示例:

#include <stdio.h>
#include <setjmp.h>
#include <assert.h>

#define MAXDEPTH 10
jmp_buf stack[MAXDEPTH];
int sp = 0;

#define CALL(f) \
do { \
assert(sp < MAXDEPTH); \
if (setjmp(stack[sp++]) == 0) { \
f; \
} \
} while (0)
#define RETLEVEL(n) \
do { \
if ((n) > 0) { \
sp -= (n); \
assert(sp >= 0 && sp < MAXDEPTH); \
longjmp(stack[sp], 1); \
} \
} while (0)
#define RETURN \
do { \
sp -= 1; \
assert(sp >= 0); \
return; \
} while (0)

void f3(void) {
printf("In f3(), sp is %d, returning back 2 levels\n", sp);
RETLEVEL(2);
}

void f2(void) {
printf("In f2(), calling f3(), sp is %d\n", sp);
CALL(f3());
printf("Returning from f2(), sp is %d\n", sp);
RETURN;
}

void f1(void) {
printf("In f1(), calling f2(), sp is %d\n", sp);
CALL(f2());
printf("Returning from f1(), sp is %d\n", sp);
RETURN;
}

int main(void) {
printf("In main(), calling f1(), sp is %d\n", sp);
CALL(f1());
printf("Returning from main(), sp is now %d\n", sp);
return 0;
}

编译并运行时,输出:

In main(), calling f1(), sp is 0
In f1(), calling f2(), sp is 1
In f2(), calling f3(), sp is 2
In f3(), sp is 3, returning back 2 levels
Returning from f1(), sp is 1
Returning from main(), sp is now 0

不过,请仔细阅读这些函数,因为它们带有一些关于局部变量在 setjmp() 返回之间保存其值的警告。


对于具有内置多级返回的语言... tcl 浮现在脑海中的是 return -level N 。不过,任何具有延续性的语言(例如方案或协程)都可以轻松模拟它。

关于c - 如何在C中实现return *语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60797359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com