为什么不嵌套的C标准支持的功能? [英] Why are nested functions not supported by the C standard?

查看:103
本文介绍了为什么不嵌套的C标准支持的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它似乎并不像它会太硬装配来实现。

It doesn't seem like it would be too hard to implement in assembly.

海湾合作委员会也有一个标志(-fnested函数),使它们的使用。

gcc also has a flag (-fnested-functions) to enable their use.

推荐答案

原来,他们不是真的那么容易正确地实现。

It turns out they're not actually all that easy to implement properly.

如果一个内部函数可以访问包含范围内的变量?
如果不是,有一个在筑巢它没有任何意义;只是让静态的(限制能见度翻译单元它在),并添加评论说:这不过是个MYFUNC使用的辅助函数()。

Should an internal function have access to the containing scope's variables? If not, there's no point in nesting it; just make it static (to limit visibility to the translation unit it's in) and add a comment saying "This is a helper function used only by myfunc()".

如果您希望获得包含范围内的变量,不过,你基本上迫使其产生封锁(另一种方法是限制你可以嵌套函数足以让他们没用做什么)。
我认为,GCC实际上是由生成(在运行时)为包含函数,即建立一个上下文指针在每次调用一个独特的thunk处理这个,然后调用嵌套函数。这最终被一个相当恶心劈和东西一些完全合理的实现不能做(例如,禁止写入存储器的执行的系统 - 其中许多现代操作系统的出于安全原因,这样做)。
唯一合理的途径,使其在一般的工作是迫使所有的函数指针随身携带隐藏上下文参数,并且所有的函数接受它(因为在一般情况下,你不知道,当你调用它是否是一个封闭或不未闭合的功能)。这是不恰当的在C需要技术和文化的原因,所以我们坚持或者使用明确的上下文指针假一结束,而不是嵌套功能,还是使用的基础设施需要一个更高层次的语言的选择做正确。

If you want access to the containing scope's variables, though, you're basically forcing it to generate closures (the alternative is restricting what you can do with nested functions enough to make them useless). I think GCC actually handles this by generating (at runtime) a unique thunk for every invocation of the containing function, that sets up a context pointer and then calls the nested function. This ends up being a rather Icky hack, and something that some perfectly reasonable implementations can't do (for example, on a system that forbids execution of writable memory - which a lot of modern OSs do for security reasons). The only reasonable way to make it work in general is to force all function pointers to carry around a hidden context argument, and all functions to accept it (because in the general case you don't know when you call it whether it's a closure or an unclosed function). This is inappropriate to require in C for both technical and cultural reasons, so we're stuck with the option of either using explicit context pointers to fake a closure instead of nesting functions, or using a higher-level language that has the infrastructure needed to do it properly.

这篇关于为什么不嵌套的C标准支持的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆