有没有办法在 C 中引用你所在的函数?
我正在编写一个函数,它只是查找表内的值。是否可以在其内部调用该函数?我看过有关 this
和 self
的内容,但不太理解。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我正在编写一个函数,它只是查找表内的值。是否可以在其内部调用该函数?我看过有关 this
和 self
的内容,但不太理解。
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(4)
请参阅递归(计算机科学)(维基百科)。
在函数内部调用函数的示例:
See Recursion (computer science) (Wikipedia).
An example of calling a function inside a function:
其他人已经回答了你的问题,但由于它对你来说很陌生,你可能想阅读递归和递归函数。如果您不知道的话,有些问题可能会引起您的注意。
最糟糕的是,如果堆栈太深,或者函数堆栈分配了很多东西,堆栈很快就会溢出。如果您计划使用递归实现,请确保您的递归是有界的,并且您在堆栈上分配了最低限度的空间。
您可能需要考虑迭代方法 - 每个递归问题都可以通过一些思考迭代解决。这通常也是一个有趣的练习。
JoshLeaves 说过递归更快,但通常并不是因为需要分配增长堆栈和设置寄存器。如果您的函数对自身进行两次或多次调用来计算其结果,那么迭代解决方案总是更快。
Others have answered your question, but since it was alien to you, you might want to read up on recursion and recursive functions. There are some gotchas that may catch you if you are not aware.
The worst of which is that you can quickly overflow your stack if you are too deep, or if your function stack-allocates a lot of things. If you are planning to use a recursive implementation make sure your recursion is bounded and that you allocate the bare minimum on the stack.
You might want to consider an iterative approach - every recursive problem can be solved iteratively with some thought. It's usually an interesting exercise to do as well.
JoshLeaves has said that recursion is faster, but often it's not because of the need to allocate grow stack and set up registers. If your function makes two or more calls to itself to calculate its result then an iterative solution is always faster.
更新
好吧,我以为这是关于“获取每个函数值”。正如其他发帖者所说,这称为递归。但有一些注意事项:
递归比迭代更快(我手头没有基准测试结果,但我一年前在 英特尔酷睿 i5)。
Update
Okay, I thought this was about "getting every function value". As other posters said, this is called recursion. A few notes though:
Recursion is faster than iteration (I don't have benchmark results on hand, but I ran them one year ago on an Intel Core i5).
是的,你可以。这就是所谓的递归。
当然,您需要从中返回以避免无限递归调用。无法返回会导致堆栈溢出。这是一个更好的例子:
Yes, you can. It's called recursion.
Of course you need to return from it to avoid infinite recursive calls. Failing to return will cause a stack overflow. Here's a better example: