C 语言中打破递归的惯用方法是什么?

发布于 2025-01-06 21:23:39 字数 1431 浏览 0 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

傾旎 2025-01-13 21:23:39

选项有:

  1. f() 返回一个状态标志,指示成功或失败。这会导致错误从发生错误的深度一次上升一级,因此可能不是您想要的。请注意,如果您需要解除 f() 可能在每个级别声明的任何分配或释放资源,这是唯一安全的选择。

  2. 完全按照您的建议使用setjmp()longjmp()来模拟抛出异常的效果并直接跳转到错误处理代码。

Options are:

  1. Return a status flag from f() indicating success or failure. This causes the error to bubble up one level at a time from the depth at which the error occurs, so may not be what you want. Note that this is the only safe option if you need to unwind any allocations or release resources which f() may have claimed at each level.

  2. Use setjmp() and longjmp() exactly as you suggest to simulate the effect of throwing an exception and jump directly to the error-handling code.

秋心╮凉 2025-01-13 21:23:39

通常的方式是返回一个指示错误的值,大多使用-1

The usual way is it return a value indicating an error, mostly -1 is used.

染柒℉ 2025-01-13 21:23:39

我认为 longjmp 是正确的选择。不过,我根本不认为这是好的编码风格。
如果您开始在代码中引入跳转,那么就很难看出代码的作用。还有很多问题:

  • 代码可读性受到影响,
  • 您只能从一个地方调用函数,因此代码的重用受到严重限制
  • 使用 longjmp 时很容易引入内存泄漏
  • 结果代码更加脆弱(更容易中断,例如在引入setjmp 上方的某些代码)

除非您有非常具体的性能要求,否则请尽量避免它,而是让错误结果返回到原始调用者。

I think longjmp is the way to go. I would not at all consider it good coding style, though.
It becomes harder to see what your code does if you start introducing jumps in it. There are also numerous problems:

  • code readability suffers
  • you can only call your function from one place, thus reuse of the code is severely limited
  • it's easy to introduce memory leaks when using longjmp
  • the resulting code is much more brittle (breaks easier, for example when introducing some piece of code above the setjmp)

Unless you have very specific performance requirements, try to avoid it and instead let an error result bubble back down to your original caller.

妳是的陽光 2025-01-13 21:23:39

如果递归很深,我认为 longjmp 更有意义。否则,返回会花费额外的 O(N) (其中 N 是递归级别数),其中包括使用大量堆栈帧页面来破坏 cpu 缓存(每个堆栈帧可能是一个完整的缓存行)。

有些人会认为 longjmp 是“糟糕的风格”,我同意,但无论如何使用深度递归已经是更糟糕的风格了......(并且可能会产生更糟糕的效果,比如吹走你的堆栈并使程序崩溃或产生特权妥协,而不仅仅是看起来丑陋。)

If the recursion will be deep, I would think longjmp makes more sense. Otherwise returning costs an extra O(N) (where N is the number of levels of recursion), and that includes thrashing the cpu cache with tons of pages of stack frames (each stack frame is likely to be a whole cache line).

Some will argue that longjmp is "bad style", and I will agree, but using deep recursion is much worse style already anyway... (And likely to have much worse effects, like blowing away your stack and crashing the program or yielding privilege compromise, not just looking ugly.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文