gpt4 book ai didi

c - 为什么函数在 C 中不被视为一等公民

转载 作者:行者123 更新时间:2023-12-04 11:49:13 24 4
gpt4 key购买 nike

在 C(以及许多其他“低级”语言)中,函数有一个类型。您可以声明一个类型与函数匹配的变量,并且可以将函数分配给这样的变量,但人们坚持认为函数不是 C 中的一等公民。

使用指向函数的指针并将函数作为参数传递给其他函数是 C 中几个标准函数的关键; qsort例如,需要传递一个比较函数,否则它什么也做不了。

通过声明 struct,在 C 中看到“面向对象”编程的情况并不少见。具有多个函数类型的变量。回调可以并且经常是(如果不是总是——我无法想象任何其他方式来做到这一点)使用具有函数类型的变量或 struct 来实现。 s 具有函数类型的成员。

那么,为什么函数在 C 中不被认为是一等公民呢?

(我确定这是重复的,但我似乎在这里找不到任何类似的问题)

最佳答案

有一个 really good answer by Andreas Rossberg关于 Scala 问题(接近重复),它恰好解释了为什么 C/C++ 中的函数不是一等函数。报价:

Being "first-class" is not a formally defined notion, but it generally means that an entity has three properties:

  1. It can be used, without restriction, wherever "ordinary" values can, i.e., passed and returned from functions, put in containers, etc.

  2. It can be constructed, without restriction, wherever "ordinary" values can, i.e., locally, in an expression, etc.

  3. It can be typed in a way similar to "ordinary" values, i.e., there is a type assigned to such an entity, and it can be freely composed with other types.

For functions, (2) particularly implies that a local function can use all names in scope, i.e. you have lexical closures. It also often comes with an anonymous form for construction (such as anonymous functions), but that is not strictly required (e.g. if the language has general enough let-expressions). Point (3) is trivially true in untyped languages.

...

  • Functions in C/C++ are not first-class. While (1) and (3) are arguably available through function pointers, (2) is not supported for functions proper. (A point that's often overlooked.)

强调我的

关于c - 为什么函数在 C 中不被视为一等公民,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48092176/

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